File: injecting_context.rst

package info (click to toggle)
cookiecutter 2.6.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,780 kB
  • sloc: python: 6,097; makefile: 113; sh: 8
file content (54 lines) | stat: -rw-r--r-- 1,344 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
.. _injecting-extra-content:

Injecting Extra Context
-----------------------

You can specify an ``extra_context`` dictionary that will override values from ``cookiecutter.json`` or ``.cookiecutterrc``:

.. code-block:: python

    cookiecutter(
        'cookiecutter-pypackage/',
        extra_context={'project_name': 'TheGreatest'},
    )

This works as command-line parameters as well:

.. code-block:: bash

    cookiecutter --no-input cookiecutter-pypackage/ project_name=TheGreatest

You will also need to add these keys to the ``cookiecutter.json`` or ``.cookiecutterrc``.


Example: Injecting a Timestamp
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

If you have ``cookiecutter.json`` that has the following keys:

.. code-block:: JSON

    {
        "timestamp": "{{ cookiecutter.timestamp }}"
    }


This Python script will dynamically inject a timestamp value as the project is
generated:

.. code-block:: python

    from cookiecutter.main import cookiecutter

    from datetime import datetime

    cookiecutter(
        'cookiecutter-django',
        extra_context={'timestamp': datetime.utcnow().isoformat()}
    )

How this works:

1. The script uses ``datetime`` to get the current UTC time in ISO format.
2. To generate the project, ``cookiecutter()`` is called, passing the timestamp
   in as context via the ``extra_context``` dict.