[英]Django: Inject a string variable from Views.py with HTML and Django template tags into HTML file
所以這是我的問題:我有一個包含 HTML 和Django 模板標簽的 Python 字符串,並希望在我轉到該頁面時將其注入到基本 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)
基本文件
{% load static %}
...
{{ html | safe }}
...
當我使用python3 manage.py runserver
在本地機器上運行應用程序並轉到呈現 base.html 的 URL 時,我將看到的所有內容是Hello world {{ code }}
,並且不執行 Javascript 代碼。 我想查看 Views.py 文件中 html 字典中'code'
鍵的實際值,而不是{{ code }}
。
如果我的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 文件)?
Django 模板引擎不會在注入的字符串中呈現(解析)模板代碼。 為此,您必須通過以下任一方式手動呈現模板代碼:
Template
對象並將結果字符串傳遞給你的base.html
,html
上下文變量的值移動到模板文件,並使用render_to_string()
。 如果您決定使用最后一個,您絕對應該考慮在base.html
使用include
模板標記(而不是使用render_to_string()
手動渲染),因為它減少了手動工作量並且是首選的渲染方式另一個模板中的模板代碼。
您可以使用文件寫入來完成此任務。 在模板文件夾中創建一個 newfile.html ,你可以這樣做
視圖.py
html_tag = "{% extends \"yourapp/base.html\"%}"+"{% block content %}"
html_tag +="<p>Hello world {{ code }}</p> <script src=\"{% static \"appName/javascript_code_example.js\" %}\"></script>"
html_tag +="{% endblock content %}"
html_file = open('yourapp/templates/yourapp/newfile.html', "w")
html_file.write(html_tag)
html_file.close()
html = {
'code': code
}
return render(request, r'yourapp\newfile.html', html)
在 base.html 中
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<p>Your base code</p>
<!--The part of code you want to retrieve from views.py file-->
{% block content %}{% endblock content %}
</body>
</html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.