1

We have the file cookiecutter.json, which defines the default context for a template. I would like to specify, via a command flag, something like:

cookiecutter --no-input --context my-context.json <cookiecutter-template>

So that the same template can be used to generate different projects, without having to enter the data manually on the input prompts. There is a workaround to achieve this:

  1. clone the template repo locally
  2. modify the cookiecutter.json in the template repo
  3. specify as template the local clone, and not the github clone

This is less than ideal, because it requires modifying a repository, does not allow for independent storage of the context files, and does not allow to use the same template to easily create different projects.

Is there a way to specify the context to cookiecutter, on the command line?

1 Answer 1

0

No (Not Exactly)

From what I can see there is no current way using a command line flag in the exact way you wish for.

However based on my research for this exact same problem there are two main avenues to solve this, each more or less appropriate depending on the exact situation.

Standard/Personal Context Values

In the case where you have standard, usually personal context values you wish to use over multiple projects there is the option of adding a user specific configuration.

It seems you can specify some default context settings into a .cookiecutterrc file in your home directory. (Current documentation can be found here). This is most aptly used for things such as email address, full name, github account name etc which are fairly static.

The format of the config file is yaml and an example structure would be as follows:

default_context:
    full_name: "Gavin Cooper"
    email: "[email protected]"
    github_username: "gjcooper"

I would assume that this relies on fields such as this being given standard names across most cookiecutter packages.

Project Specific Context Values

This solution is for when you have a project management software or other script where you want to generate project specific values (ie app_name) into the cookiecutter json format and then automatically generate your project directory structure without user input.

This requires writing a very short python script to hook into the cookiecutter internals, but is simple to use:

from cookiecutter.main import cookiecutter
import json

with open('project_context.json') as jfile:
    mycontext = json.load(jfile)

cookiecutter('<local or remote cookiecutter template file>',
             extra_context=mycontext,
             no_input=True)

This solution I can verify has worked for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.