Reputation: 1725
How to render jinja code on template?
For instance, I have a route that need to render jinja code on the given HTML template like this:
from app import app
from flask import render_template
from jinja2 import Template
@app.route('/View/Package')
def getView():
HtmlDesc="""
<div class="codehilite"><pre><span></span><span class="p">{{</span><span class="n">cookiecutter</span><span class="o">.</span><span class="n">repo_name</span><span class="p">}}</span><span class="o">/</span><span class="p">{{</span><span class="n">cookiecutter</span><span class="o">.</span><span class="n">repo_name</span><span class="p">}}</span><span class="o">/</span><span class="p">{{</span><span class="n">cookiecutter</span><span class="o">.</span><span class="n">repo_name</span><span class="p">}}</span><span class="o">.</span><span class="n">py</span>
</pre></div>
"""
return render_template('package.html', html=Template(HtmlDesc).render())
On the template, I tried to escape jinja code with {% raw %}..{% endraw %}
and {% filter escape %} .. {% endfilter %}
as documented here but it still does not work:
<h1>Project Description</h1>
<div class="project-description">
{% raw %}{% filter escape %}{{html|safe}}{% endfilter %}{% endraw %}
</div>
</div>
With exception:
TemplateSyntaxError: unexpected '<'
I know the error is at {{</span><span...
and class="p">}}
, value of HtmlDesc
, therefore I am looking for a proper way to escape these kind of characters of jinja in order to render this jinja code on template correctly. Thanks.
Added
What I am trying to achieve is I want the html
and jinja
code of HtmlDesc
to be interpreted and render properly on web browser. In my real application, the text above is not a fixed value as in above example snippet, it reads value from text file README
which includes inside python package and converted into HTML code. The example text above it is read from python package cookiecutter.
Upvotes: 1
Views: 2132
Reputation: 943
Add a | safe to the end of whatever you want to display. It will render it out. Make it a string too.
Inside the template you seem to be missing the |safe
in the {{ }}
inside the Markup
Also you have to remove the Template()
to make sure that the whole string is escaped
Upvotes: 1