Cookiecutter: Come up with a better way to represent the escaped {, {{, }, }}

Created on 14 Aug 2013  路  3Comments  路  Source: cookiecutter/cookiecutter

Escaping curly braces in Jinja2 is possible, but it looks awful:

{{ "{" }}
{{ "{{" }}
{{ "}" }}
{{ "}}" }}

{{ {{ url_for('home') }} }}

{% raw %}
<p>Go <a href="{{ url_for('home') }}">Home</a></p>
{% endraw %}

What about supporting something else, since this is a common task? Some possibilities:

Option 1: Use a backslash, like \{ and \{\{

Pro: simple, intuitive.
Con: what if you really want a backslash, like if you're templating Windows paths?

Option 2: Precede brace with an unusual character, like 鈽儃 and 鈽儃鈽儃

Unicode snowmen look kinda like curly braces.

Pro: Avoids the con of option 1, since using this combination is rare.
Con: Hard to type, and kind of weird.

Option 3: Surround them with a character, like _{_ and _{{_

Pro: Don't have to escape every single one, making it more readable.
Con: What if you really wanted to type _{_? Is that ever a common thing to type, in any popular framework?

enhancement

Most helpful comment

For anyone else looking here I would recommend using raw blocks when working with larger jinja blocks inside cookiecutter.

E.g.:

{% raw -%}
{{ foo }} and {{ bar }}
...
{{ baz }}
{%- endraw %}

yields

{{ foo }} and {{ bar }}
...
{{ baz }}

It was useful for me when generating Ansible templates with cookiecutter.

All 3 comments

Nah, I don't think it's necessary after all. (But if anyone cares about this, please comment.)

I don't immensely care, but it's worth pointing out that a person can also change the default delimiters if it comes up often enough:

Or you could simply have {{{ be interpreted as a single {, and }}} as a single }, although that'd probably mess with syntax highlighting.

For anyone else looking here I would recommend using raw blocks when working with larger jinja blocks inside cookiecutter.

E.g.:

{% raw -%}
{{ foo }} and {{ bar }}
...
{{ baz }}
{%- endraw %}

yields

{{ foo }} and {{ bar }}
...
{{ baz }}

It was useful for me when generating Ansible templates with cookiecutter.

Was this page helpful?
0 / 5 - 0 ratings