jinja2 with three curly braces without including an extra white space

Viewed 835

Jinja2 correctly renders three curly braces next to each other if a white space is inserted, as shown in Case 1 below. However, without a white space an exception is thrown, case 2 below. White spaces are here indicated with red bars.

Is it possible to render an output without including white spaces, that is render an output like \textbf{Hello, World!}?

jinja2 throws an exception for three curly braces without a white space

A python code example is listed below

from jinja2 import Template


template_1 = Template(r"\textbf{ {{msg}} }")

#template_2 = Template(r"\textbf{{{msg}} }") # Throws an exception

msg = "Hello, World!"

out_1 = template_1.render({'msg':msg})
#out2 = template_2.render({'msg':msg}) # FAILS!


print(out_1)

Output

\textbf{ Hello, World! }

What I would like to have is

\textbf{Hello, World!}
3 Answers

the best solution I have found is to use the {% raw %} tag for embracing exclusively one curly brace:

template_1 = Template(r"\textbf{% raw %}{{% endraw %}{{msg}}{% raw %}}{% endraw %}")

This will render

\textbf{Hello, World!}

as desired.

just a slight improvement to pedro-juan's answer:

\hspace{0pt} is a non-unicode latex-way to insert a "Zero-Width Space" (unicode U+200B) which convinces the parser to not-treat "{{{" as something causing an error.

Template(r"\textbf{% raw %}{{% endraw %}{{msg}}

should produce the same output as

Template(r"\textbf\hspace{0pt}{{msg}}")

It's also possible to change all the jinja2-markers, which might make it easier for some syntax highlighter to not get confused by non-matching curly-brace pairs. (at least my vim does a not-so-decent job with latex-jinja2) (see this article)

e.g.

latex_jinja_env = jinja2.Environment(
    block_start_string = '\BLOCK{',
    block_end_string = '}',
[...]

Have you tried to add '-' after {{ and before }}?

template_2 = Template(r"\textbf{ {{-msg-}} }")

This will remove the whitespaces. So you can keep whitespaces between single/double curly braces into templates and Jinja2 remove them during rendering.

Related