Issue
I have a Flask app that looks as follows:
@app.route('/')
def index():
headline = render_template('headline.html', headline = 'xyz') #-> return <h1>xyz</h1>
return render_template('page.html', headline = headline) # insert headline html into a page
headline.html
is a template which imports a jinja macro from a macro file (macros.html
). The macro generates the headline.
headline.html
:
{% import 'macros.html' as macros %}
{{ macros.get_headline(headline) }}
macros.html
:
{% macro get_headline(headline) %}
<h1>{{ healine }}</h1>
{% endmacro %}
My question is - is it possible to call the macro to get headline
without the need to call the template headline.html
?
Ideally, I'd like to see
@app.route('/')
def index():
headline = # somehow call get_headline('xyz') from macros.html
return render_template('page.html', headline = headline) # insert headline html into a page
Solution
Instead of rendering the template from a file, you can render a template from a string. So you can call your macro from a string.
from flask.templating import render_template_string
@app.route('/')
def index():
headline = render_template_string(
"{% import 'macros.html' as macros %}"
"{{ macros.get_headline(headline) }}",
headline='xyz'
)
return render_template('page.html', headline=headline)
(ignoring the typo healine
instead of headline
in macros.html)
Answered By - Sven Eberth
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.