Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you display markdown value using jinja2?

I process a string on the server using python markdown2 module.

marked_up = '    import sys\n    print "hello there"' 
marked_up = unicode(markdown2.markdown(marked_up, extras=["fenced-code-blocks"]))

Then, I pass the value through jinja2 to the client:

template_value = {'marked_up': marked_up}

template = JINJA_ENVIRONMENT.get_template('index.html')
self.response.write(template.render(template_value))

In the index.html I try to display this marked value:

<div class="row marketing" id="my_row_mark">

   {{ marked_up }}

</div>

The problem is that the text is shown with the html attributes:

<pre><code>import sys print "hello there" </code></pre>

I would like to see only:

import sys print "hello there"

with the proper markdown applied by markdown2.

like image 561
LLaP Avatar asked Oct 12 '14 12:10

LLaP


1 Answers

TL;DR:

Use the |safe filter to prevent your content from getting automatically escaped:

{{ marked_up|safe }}



Jinja2 has a configuration option named autoescape that determines if content in templates should be automatically HTML escaped or not.

By default (if you're using plain Jinja2) autoescaping is disabled. But if your using a framework that integrates Jinja2, autoescape may very well be enabled.

So when autoescaping is enabled, any content you pass into a template will be HTML escaped. Note in this example how content will be escaped, which leads to you seeing the HTML tags in the rendered HTML:

example.py

from jinja2 import Environment, FileSystemLoader

env = Environment(loader=FileSystemLoader('.'),
                  autoescape=True)              # <-- autoescaping enabled

template = env.get_template('index.html')
content = "<strong>bar</strong>"
print template.render(content=content)

index.html

<div>
    {{ content }}
</div>

Output:

<div>
    &lt;strong&gt;bar&lt;/strong&gt;
</div>

You can now prevent escaping for a particular variable by using the |safe filter:

<div>
    {{ content|safe }}
</div>

Output:

<div>
    <strong>bar</strong>
</div>

For more details, see the documentation on HTML escaping.

like image 181
Lukas Graf Avatar answered Oct 19 '22 18:10

Lukas Graf