Skip to content

Define and use custom Jinja2 filters #547

@chekunkov

Description

@chekunkov

Custom filters can make templating even more flexible. E.g. if I want to create nicely formatted .rst file in new project I should do something like this:

{% for _ in cookiecutter.project_name %}={% endfor %}
{{ cookiecutter.project_name }}
{% for _ in cookiecutter.project_name %}={% endfor %}

to produce

====================
My cool project name
====================

Looks cumbersome, right? How cool would it be to do something like this instead:

{{ cookiecutter.project_name|rst_h1 }}

Unfortunately there's no way to access Jinja2 environment before rendering a template - thus no way to add custom filters.

I was thinking about following approach - add filters directory, where developer can place python modules with custom filters, import functions from those modules after environment instantiation and update env.filters. This should be simple to implement and if you give me a green light I'll submit a PR.

P.S. Actually I would love to have some way to access environment directly - then it would be unnecessary to do stuff described above. But I'm not sure how it could be implemented - maybe there could be some convention, like environment.py file in template root with update_environment(env) function... Seems clumsy, don't like this idea too much, so please share your thoughts.

Metadata

Metadata

Assignees

No one assigned

    Labels

    discussionenhancementThis issue/PR relates to a feature request.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions