ImportError: cannot import name ‘escape’ from ‘jinja2’

Jinja is a dependency of Flask and Flask V1.X.X uses the escape module from Jinja, however recently support for the escape module was dropped in newer versions of Jinja. To fix this issue, simply update to the newer version of Flask V2.X.X in your requirements.txt where Flask no longer uses the escape module from Jinja. … Read more

Is there an idiomatic file extension for Jinja templates?

2021 update:: Jinja now officially recommends using the extension .jinja. check docs Update: Things changed since I wrote this answer, .jinja2 and .j2 are trending. Jinja Authors did not define a default extension. Most of Jinja template editors like Vim extension, TextMate extension, Emacs extension, and PyCharm mention no default extension to enforce Jinja highlighting. … Read more

How do I render jinja2 output to a file in Python instead of a Browser

How about something like this? from jinja2 import Environment, FileSystemLoader env = Environment(loader=FileSystemLoader(‘templates’)) template = env.get_template(‘test.html’) output_from_parsed_template = template.render(foo=’Hello World!’) print(output_from_parsed_template) # to save the results with open(“my_new_file.html”, “w”) as fh: fh.write(output_from_parsed_template) test.html <h1>{{ foo }}</h1> output <h1>Hello World!</h1> If you are using a framework, such as Flask, then you could do this at the … Read more

Ansible: filter a list by its attributes

To filter a list of dicts you can use the selectattr filter together with the equalto test: network.addresses.private_man | selectattr(“type”, “equalto”, “fixed”) The above requires Jinja2 v2.8 or later (regardless of Ansible version). Ansible also has the tests match and search, which take regular expressions: match will require a complete match in the string, while … Read more