python - Django:将带有 HTML 和 Django 模板标签的 Views.py 中的字符串变量注入 HTML 文件
问题描述
所以这是我的问题:我有一个 Python 字符串,它同时包含 HTML 和Django 模板标签,并希望在我转到该页面时将其注入到基本 HTML 文件中。虽然,当我进入页面时,所有的 HTML 都会呈现,但 Django 模板标签不会,并且被视为字符串?
这是该问题的简化示例:
视图.py
def page(request, code):
html = {
'code': code
'html': """<p>Hello world {{ code }}</p> <script src="{% static 'appName/javascript_code_example.js' %}"></script>"""
}
return render(request, 'base.html', html)
base.html
{% load static %}
...
{{ html | safe }}
...
当我在本地计算机上运行应用程序python3 manage.py runserver
并转到呈现 base.html 的 URL 时,我将看到的只是Hello world {{ code }}
,并且未执行 Javascript 代码。而不是{{ code }}
我想'code'
在 Views.py 文件中查看 html 字典中键的实际值。
如果我的base.html文件如下:
{% load static %}
...
<p>Hello world {{ code }}</p>
<script src="{% static 'appName/javascript_code_example.js' %}"></script>
...
然后将启用 Javascript,我将Hello world value_of_code_variable
在屏幕上看到。
解决方案
您必须加载具有模板库函数的 python 脚本。另外,为什么要将字符串呈现为 html 而不是创建 html 模板?(带有模板语法的html文件)?
推荐阅读
- ios - iOS 应用深层链接和 Firebase 动态链接在应用转移后不起作用
- automata-theory - 我可以在形成字符串的字符之间写空字符串吗?
- strapi - Strapi 错误:列指定了多次
- nativescript - Nativescript:来自在线游乐场的项目
- neo4j - 无法调用过程“ga.timetree.now”:java.lang.NoClassDefFoundError:com.graphaware.module.timetree.SingleTimeTree
- subscription - Fiware Draco 订阅中的“onlyChangedAttrs”布尔标志不起作用
- javascript - Angular 9:自定义组件是一个有效的 mat-menu-item
- javascript - 当用户能够在其中搜索数据时,我如何才能延迟加载表?
- ubuntu - 如何在 Ubuntu 20.04 上使用 Cloud-init 设置自定义密码?
- c# - Winforms 文本框允许用户只输入字母、数字、点和单词之间的空格。正则表达式