File: local_extensions.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 (58 lines) | stat: -rw-r--r-- 1,912 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
55
56
57
58
.. _`local extensions`:

Local Extensions
----------------

*New in Cookiecutter 2.1*

A template may extend the Cookiecutter environment with local extensions.
These can be part of the template itself, providing it with more sophisticated custom tags and filters.

To do so, a template author must specify the required extensions in ``cookiecutter.json`` as follows:

.. code-block:: json

    {
        "project_slug": "Foobar",
        "year": "{% now 'utc', '%Y' %}",
        "_extensions": ["local_extensions.FoobarExtension"]
    }

This example uses a simple module ``local_extensions.py`` which exists in the template root, containing the following (for instance):

.. code-block:: python

    from jinja2.ext import Extension


    class FoobarExtension(Extension):
        def __init__(self, environment):
            super(FoobarExtension, self).__init__(environment)
            environment.filters['foobar'] = lambda v: v * 2

This will register the ``foobar`` filter for the template.

For many cases, this will be unnecessarily complicated.
It's likely that we'd only want to register a single function as a filter. For this, we can use the ``simple_filter`` decorator:

.. code-block:: json

    {
        "project_slug": "Foobar",
        "year": "{% now 'utc', '%Y' %}",
        "_extensions": ["local_extensions.simplefilterextension"]
    }

.. code-block:: python

    from cookiecutter.utils import simple_filter


    @simple_filter
    def simplefilterextension(v):
        return v * 2

This snippet will achieve the exact same result as the previous one.

For complex use cases, a python module ``local_extensions`` (a folder with an ``__init__.py``) can also be created in the template root.
Here, for example, a module ``main.py`` would have to export all extensions with ``from .main import FoobarExtension, simplefilterextension`` or ``from .main import *`` in the ``__init__.py``.