Django模板:如何显示html代码?
我试图在博客中显示一些HTML标记,并想知道是否有一种方法可以直接包装Django模板的一部分,而无需将其放入上下文变量中 例如,我想输出一组代码,其中一些是JavaScript,一些是HTML,还有一些是CSS。如果我直接在Django模板中输入代码,并将其包装在一些预标记中:Django模板:如何显示html代码?,html,django,templates,escaping,Html,Django,Templates,Escaping,我试图在博客中显示一些HTML标记,并想知道是否有一种方法可以直接包装Django模板的一部分,而无需将其放入上下文变量中 例如,我想输出一组代码,其中一些是JavaScript,一些是HTML,还有一些是CSS。如果我直接在Django模板中输入代码,并将其包装在一些预标记中: <pre> /* Here is the markup I want to display: */ ... lots of HTML </pre> 展示 > 我应该
<pre>
/* Here is the markup I want to display: */
... lots of HTML
</pre>
展示
>
我应该用
>
<h1> Heading Level 1 </h1>
我尝试在代码部分周围添加Django标记{%autoescape on%},但没有效果,因为我没有呈现上下文变量
我想知道是否有比用替换每次出现的您必须使用xmp标记
{% autoescape off %}
{{your_variable_here}}
{% endautoescape %}
测试Html
只需将变量包装在下面的Django模板标记中即可
from django.template.loader import render_to_string
rendered = render_to_string('my_template.html', {'foo': 'bar'})
将HTML代码放在“your_variable_here”变量中,Django会将其显示为HTML。所有HTML标记都会工作
编辑:
对不起,我遗漏了重要的部分。
在视图中这样做
{% autoescape off %}
{{rendered}}
{% endautoescape %}
并将此渲染字符串传递给模板变量,并通过放置行在其他模板内渲染给定模板
<pre>
<code>
{% filter force_escape %}
<span class="hello">Anything HTML really</span>
{% endfilter %}
</code>
</pre>
这个问题由来已久,但它会在搜索引擎上突然出现,在我看来,没有一个答案是正确的 萨威克·卡比克(Sławek Kabik)的不受欢迎,斯密特·帕特尔(Smit Patel)的过于复杂(视图膨胀) 为了执行OP要求的操作,您必须在
{%filter%}
标记中使用强制退出
内置过滤器
例如:
考虑使用TinyMCE这样的所见即所得编辑器。它将自动转换
地狱,太棒了!我甚至不知道它存在。当我试图显示通过POST请求提交的按钮的代码时,它对我不起作用。根据mozilla文档,xmp
元素已被弃用。
{% autoescape off %}
{{your_variable_here}}
{% endautoescape %}
from django.template.loader import render_to_string
rendered = render_to_string('my_template.html', {'foo': 'bar'})
{% autoescape off %}
{{rendered}}
{% endautoescape %}
<pre>
<code>
{% filter force_escape %}
<span class="hello">Anything HTML really</span>
{% endfilter %}
</code>
</pre>