github linkedin email rss
How to template a LaTeX paper with cookiecutter
Sep 27, 2017
2 minutes read

Cookiecutter is a command line utility written in python to create templated files and directory structures.

Why?

When I finally have something to write about as a paper to be submitted to a journal, I found myself copying the files from my previous paper again and again, delete much of it (contents of the old paper), and modify some parts for the new paper. Of course, it’s not that hard to do that everytime, but cookiecutter is a useful tool to streamline this.

How?

It’s easy to make your own cookiecutter template. In cookiecutter, you can have template variables that the user will be prompted to set when the template is being generated. You specify this in cookiecutter.json, which, in this case, looks like

{
  "paperdir": "paper",
  "texfile": "ms",
  "papertitle": "Enter paper title",
  "authors": "Semyeong Oh",
  "_copy_without_render": [
        "aasjournal.bst",
        "aastex61.cls",
        ".gitignore"
    ]
}

It’s very simple with four template variables that I want to customize when I’m starting a draft:

  • paperdir for directory where all the files go in
  • texfile for the name of the TeX file
  • papertitle for the title of the paper
  • authors for authors

The template rendering is done with jinja2, and you can use the variables in directory/file names as well as inside the content of the file. So in this case, I have {{cookiecutter.texfile}}.tex file which, when generated, will be ms.tex (the default value) if I don’t change it. And inside that file is this block

\title{ {{cookiecutter.papertitle}} }

\author{
  {{cookiecutter.authors}}
} 

which will also be changed to appropriate values when generated.

There are also files that I simply want to copy without processing with the template engine like the LaTeX class files (.cls) or bibliography style files (.bst). That’s what _copy_without_render option is for.

This example for minimal AASTeX6.1 document is available here.

Advanced usage

There are a couple of use cases for the advanced features in cookiecutter I can think of although I never needed them and didn’t bother to do it yet.

  • If you want to generate templates for different journals, you can have a choice variable which determine what’s inside a cls file.
  • If there are certain set of LaTeX commands convenient for certain type of projects, you can probably prompt whether or not to include e.g., math macros for probabilistic model equations.

Other usages

Cookiecutter, or any similar tool, is useful for many things that has to do with generating boilerplates like python package structure with proper setup.py, custom research project structure, etc. Checkout a pantry full of cookiecutters.


Back to posts