Clare Macrae
Clare Macrae

Reputation: 3799

How to use machine-generated variables in cookiecutter

Is there a way to machine-generate some values, after the user has supplied some their values for the variables in cookiecutter.json?

The reason I ask is that:

So I'd really like to be able to remove the user prompt, and calculate the value instead.

Things I've tried:

I'm using cookiecutter on the command line:

cookiecutter path_to_template

Am I missing any tricks?

Upvotes: 11

Views: 4285

Answers (2)

zhukovgreen
zhukovgreen

Reputation: 1648

Let's say you need a new variable some_variable which equals to the cookiecutter.project_slug.replace('_', '-'). You also do not want to ask the user about this variable. That's why we need to refer it as _some_variable inside the cookiecutter.json

You can achieve this by following the further steps:

  1. Append "_some_variable": "" to the cookiecutter.json file
  2. Append into ./hooks/pre_gen_project.py the python logic which calculates the value for _some_variable, for example:
# set additional helper variables
{{ cookiecutter.update({"_some_variable": cookiecutter.project_slug.replace('_', '-')}) }}
  1. Now you can access this variable with updated value in your template files by:
"{{ cookiecutter._some_variable }}"

Credits to https://github.com/samj1912/cookiecutter-advanced-demo

Upvotes: 2

zzzirk
zzzirk

Reputation: 1592

I needed this exact capability just a few days ago. The solution I came up with was to write a wrapper script for cookiecutter, similar to what is mentioned in:

http://cookiecutter.readthedocs.io/en/latest/advanced_usage.html#calling-cookiecutter-functions-from-python

My script generates a random string for use in a Django project. I called my script cut-cut:

#! /usr/bin/env python

from cookiecutter.main import cookiecutter

import os

rstring = ''.join([c for c in os.urandom(1024)
                   if c.isalnum()])[:64]

cookiecutter(
    'django-template',     # path/url to cookiecutter template
    extra_context={'secret': rstring},
)

So now I simply run cut-cut and step through the process as normal. The only difference is that the entry named secret in my cookiecutter.json file is prepopulated with the generated value in rstring from the script, provided via the extra_context passed.

You could modify the script to accept the template via the command line, but in my usage I always use the same template, thus I simply pass a hard coded value "django-template" as noted in the code above.

Upvotes: 6

Related Questions