I'm using Tornado Templates and one of my fields is a string that has HTML tags quoted in it, e.g.
<p>Solar power</p>
When I render it into the template, the tags are quoted verbatim instead of treated as tags.
{{ quoted_html }}
So it looks exactly as above with the p tag visible.
In other templating systems, {{ = foo}} renders foo verbatim, but {{html foo}} treats the tags as tags.
Is there the equivalent in Tornado Templates?
{% raw foo %}, in Tornado 2.0+.
If you do that with a lot of expressions in a template, you can add the {% autoescape None %} directive to the beginning of the template, after which {{ foo }} will not be escaped.
Related
I'm working on a project that takes in a markdown page and converts it into HTML before inserting it into the correct document. This is the code I'm running
Python
def markdown(request, entry):
pathOfFile = "entries/" + entry + ".md"
return render(request, "encyclopedia/entry.html", {
"html_markdown": markdown2.markdown_path(pathOfFile)
})
HTML
{% block body %}
<div>
{{ html_markdown }}
</div>
{% endblock %}
And this is what is returning on the web page
<h1>CSS</h1> <p>CSS is a language that can be used to add style to an HTML page.</p>
When I inspect the source of the page the HTML is encased in quotes. Is the problem that my html_markdown variable is being read as a string? What steps can I take to get the HTML to render properly? Thanks in advance for your help!
html_markdown will contain raw HTML, so if you render that in the template, it will escape characters like < to <, etc.
You can mark the string as "safe" with the |safe template filter [Django-doc] to prevent escaping these characters:
{% block body %}
<div>
{{ html_markdown|safe }}
</div>
{% endblock %}
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.
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
I'm building an admin for Flask and SQLAlchemy, and I want to pass the HTML for the different inputs to my view using render_template. The templating framework seems to escape the HTML automatically, so all <"'> characters are converted to HTML entities. How can I disable that so that the HTML renders correctly?
To turn off autoescaping when rendering a value, use the |safe filter.
{{ something|safe }}
Only do this on data you trust, since rendering untrusted data without escaping is a cross-site scripting vulnerability.
MarkupSafe provides Jinja's autoescaping behavior. You can import Markup and use it to declare a value HTML safe from the code:
from markupsafe import Markup
value = Markup('<strong>The HTML String</strong>')
Pass that to the templates and you don't have to use the |safe filter on it.
From the Jinja docs section HTML Escaping:
When automatic escaping is enabled everything is escaped by default
except for values explicitly marked as safe. Those can either be
marked by the application or in the template by using the |safe
filter.
Example:
<div class="info">
{{data.email_content|safe}}
</div>
When you have a lot of variables that don't need escaping, you can use an autoescape override block:
{% autoescape false %}
{{ something }}
{{ something_else }}
<b>{{ something_important }}</b>
{% endautoescape %}
For handling line-breaks specifically, I tried a number of options before finally settling for this:
{% set list1 = data.split('\n') %}
{% for item in list1 %}
{{ item }}
{% if not loop.last %}
<br/>
{% endif %}
{% endfor %}
The nice thing about this approach is that it's compatible with the auto-escaping, leaving everything nice and safe. It can also be combined with filters, like urlize.
Of course it's similar to Helge's answer, but doesn't need a macro (relying instead on Jinja's built-in split function) and also doesn't add an unnecesssary <br/> after the last item.
Some people seem to turn autoescape off which carries security risks to manipulate the string display.
If you only want to insert some linebreaks into a string and convert the linebreaks into <br />, then you could take a jinja macro like:
{% macro linebreaks_for_string( the_string ) -%}
{% if the_string %}
{% for line in the_string.split('\n') %}
<br />
{{ line }}
{% endfor %}
{% else %}
{{ the_string }}
{% endif %}
{%- endmacro %}
and in your template just call this with
{{ linebreaks_for_string( my_string_in_a_variable ) }}
Use the safe filter in your template, and then sanitize the HTML with the bleach library in your view. Using bleach, you can whitelist the HTML tags that you need to use.
This is the safest, as far as I know. I tried both the safe filter and the Markup class, and both ways allowed me to execute unwanted JavaScript. Not very safe!
I have a Django template file that has a couple of enormous strings in it (images encoded in Base64). When I use the Django templating engine, it chokes and takes 5 minutes to render the template. Is there a way to exclude a part of a template, with something like:
{% ignore %}
<img src='....'>
{% endignore %}
Does this exist?
Use verbatim tag!
From django docs https://docs.djangoproject.com/en/dev/ref/templates/builtins/#verbatim
verbatim
Stops the template engine from rendering the contents of this block
tag.
A common use is to allow a JavaScript template layer that collides
with Django’s syntax. For example:
{% verbatim %}
{{if dying}}Still alive.{{/if}}
{% endverbatim %}
I have just started building my first Flask app, which currently simply returns output of inspect for my objects inside table tags. The problem is that instead of the html I expect, a template engine messes layout up creating new tags (I guess it parses dict's curly brackets).
From your question I don't really understand, why and where this inspect is ran, but it is possible to escape output like this:
{{ object | e }}
Or you can escape things inside template by using 'foo' or {% raw %}:
{{ '{{' }}
{% raw %}
{% %}
{% endraw %}