cookieninja-generator / cookieninja

A cross-platform command-line utility that creates projects from cookiecutters (project templates), e.g. Python package projects, C projects - a cookiecutter fork
BSD 3-Clause "New" or "Revised" License
68 stars 7 forks source link

Docs: suggesting changing Jinja delimiters is bad practice #69

Open GriceTurrble opened 1 year ago

GriceTurrble commented 1 year ago

Description:

From the docs on Jinja2 Custom Delimiters:

You can specify a dictionary under the _jinja2_env_vars key in the cookiecutter.json file to modify the default jinja2 delimiter ({{). This is very useful for templates which contain files that have expressions that use the default delimiters {{ ... }} such as:

  1. Helm Charts
  2. Jinja2 files

While this is technically true (and something Jinja offers so not directly a problem of this project), it's also an anti-pattern. The delimiters should be recognizable to other template authors and users without needing to go into the particulars of the template's config.

Better advice, IMO, would be to wrap their Helm Chart or other similar-syntax files in {% raw %} ... {% endraw %} tags. That way it doesn't matter what syntax is used within the file: Jinja will ignore raw blocks entirely. Template authors can then add cookiecutter variables into those templates using these tags in reverse:

{% raw %}
chart:
  # rendered by Cookiecutter/Cookieninja
  foo: {% endraw %}{{ cookiecutter.my_variable }}{% raw %}
  # left raw, interpreted by Helm
  bar: {{ .Values.helm_chart_variable }}
{% endraw %}

This may end up with slightly-uglier code in the Helm chart, granted; but it allows more progressive adoption of templating in more complex projects without needing to change the delimiter and re-write every previous template file, on top of remembering which non-standard delimiter is required for every new file.

alexander-rabenstein commented 1 year ago

I think this really depends on the use case. I want to change the delimiter, as we use cookiecutter currently to template an ansible playbook. As Ansible is using Jinja2 very heavily this would result in messing up the file with {% raw %} tags, also its messing up the ansible-lint run totally.