首页 > 解决方案 > 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在屏幕上看到。

标签: pythonhtmldjangodjango-templatesdjango-template-filters

解决方案


您必须加载具有模板库函数的 python 脚本。另外,为什么要将字符串呈现为 html 而不是创建 html 模板?(带有模板语法的html文件)?


推荐阅读