gpt4 book ai didi

django-templates - 将 html 代码从 View 传递到 Django 中的模板

转载 作者:行者123 更新时间:2023-12-01 07:34:29 25 4
gpt4 key购买 nike

我在views.py 中生成了一个html 表。我想在我的 html 模板中显示它。如果我将 html 代码作为字符串传递,像“<”这样的符号会自动替换为“& lt;”,所以我看到的是它的 html 代码而不是表格。我怎么解决这个问题?

最佳答案

只需要使用 |safe 来转义 html var过滤如下

在您的 views.py

....
context['your_html_variable '] = "<div><h1> Hello </h1></div>"
return render(request, 'template.html', context)

在您的 template.html
<body>
{{ your_html_variable|safe }}
</body>

当心 !当 html 变量来自用户而不是您时,切勿尝试对其进行转义。

关于django-templates - 将 html 代码从 View 传递到 Django 中的模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44777894/

25 4 0