I'm working on a Flask app that is working just fine, until I try to add the following line to a template to be rendered:
{% do totals.update({tier: 0}) %}
The current code for rendering the template uses Flask's render_template():
from flask import Flask, Response, request, session
from flask import render_template
app = Flask(__name__)
..
return render_template(<template.htlm>,...)
This fails with with following error:
TemplateSyntaxError: Encountered unknown tag 'do'. Jinja was looking for the following tags: 'endfor' or 'else'. The innermost block that needs to be closed is 'for'.
The obvious fix is to add the jinja2.ext.do extension to jinja. I have been able to do so successfully using Jinja2 directly, as per:
from jinja2 import Environment, PackageLoader
ENV = Environment(loader=PackageLoader('ticket_app', 'templates'), extensions=['jinja2.ext.do'])
...
TEMP = ENV.get_template('div_' + div_id + '.html')
return TEMP.render(sales_new=sales_new, event_config=event_config)
However, I would prefer to not use Jinja2 directly... The app was only using Flask and render_template() before, and as render_template() uses Jinja2 under the hood (as far as I understand) it seems that it should be possible to make render_template() understand the jinja2.ext.do extension (or any other extension for that matter).
So far, I've tried the following:
app = Flask(__name__)
app.config['TEMPLATES_AUTO_RELOAD'] = True
app.config['EXPLAIN_TEMPLATE_LOADING'] = True
env = app.jinja_env
env.add_extension('jinja2.ext.do')
While the above does not throw an error, it is also not causing it to make render_template() understand the jinja2.ext.do extension.
Any suggestions? Should this be possible? If so, how?
Update for Flask v.2.0 :
Since v.2.0, the below solution raise a KeyError: 'extensions' exception. Try this instead.
For Flask v.1.1, you can directly access to the Jinja extensions loaded by Flask with the Flask.jinja_options dictionary. In your case, adding just this line should do the trick:
app = Flask(__name__)
app.jinja_options['extensions'].append('jinja2.ext.do')
Make sure you update your Flask (using pip: pip install -U Flask).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With