How to disable Jinja2 for sections of template with {}?

This question is old but I recently had the same issue. If you setup Jinja2 Environment to use undefined=jinja2.DebugUndefined it will ignore missing parameters and leave them as if a new Jinja template. Useful for say multi-stage parsing and u can run logging as well to know when variables have not been defined:

import logging
from Jinja2 import DebugUndefined

logging.basicConfig()
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
undefined_logging = jinja2.make_logging_undefined(logger=logger, base=DebugUndefined)
jinja_env = jinja2.Environment(loader=FileSystemLoader, undefined=undefined_logging)
print(jinja2.from_string("Hello {{ worldarg }}")

This will result in a logger message such as
[date time] WARNING [<module>:lineno] Template variable warning worldarg is undefined
Hello {{ worldarg }}

Template in will have jinja rendered for passed parameters but unaltered for undefined. NOTE: This will unlikely resolve missing templates or macros defined by the routine though but standard {{ x }} types should be logged and unaltered. *Logging is also subject to how its configured as well!

Options also exist for StrictUndefined (results in exception and template processing to stop) or Undefined results in parameters passed to be removed and fields blank where expected without errors being returned to calling function.


You can usually find that information in the documentation, under "Escaping" or similar. In this case, you can either output the delimiter with a variable expression:

{{ '{{' }}

Or you can use the raw block, for longer stretches of code:

{% raw %}
    <ul>
    {% for item in seq %}
        <li>{{ item }}</li>
    {% endfor %}
    </ul>
{% endraw %}

Tags:

Python

Jinja2