我使用python markdown2模块处理服务器上的字符串.
marked_up = ' import sys\n print "hello there"'
marked_up = unicode(markdown2.markdown(marked_up, extras=["fenced-code-blocks"]))
然后,我将值通过jinja2传递给客户端:
template_value = {'marked_up': marked_up}
template = JINJA_ENVIRONMENT.get_template('index.html')
self.response.write(template.render(template_value))
在index.html中,我尝试显示这个标记的值:
<div class="row marketing" id="my_row_mark">
{{ marked_up }}
</div>
问题是文本显示为html属性:
<pre><code>import sys print "hello there" </code></pre>
我只想看到:
import sys print "hello there"
使用markdown2应用的正确降价.
解决方法:
TL; DR:
使用|safe
过滤器可防止您的内容自动转义:
{{ marked_up|safe }}
Jinja2有一个名为autoescape
的配置选项,用于确定模板中的内容是否应自动为HTML escaped.
默认情况下(如果您使用普通的Jinja2),禁用自动加载.但是如果你使用集成了Jinja2的框架,很可能会启用autoescape.
因此,当启用自动加载时,您传递到模板中的任何内容都将被HTML转义.在此示例中请注意如何转义内容,这会导致您在呈现的HTML中看到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>
输出:
<div>
<strong>bar</strong>
</div>
您现在可以使用|safe
过滤器prevent escaping for a particular variable:
<div>
{{ content|safe }}
</div>
输出:
<div>
<strong>bar</strong>
</div>
有关更多详细信息,请参阅HTML escaping上的文档.