如何使用 Django 的模板扩展变量? [英] How do I use Django's template extends variable?
问题描述
django 模板文档 提到以下用于扩展模板:
The django template doc mentions the following for extending templates:
{% extends variable %}
在哪里定义变量?是来自views.py吗?
Where do I define the variable? Is it from the views.py?
推荐答案
{% extends %}
实际上需要一个字符串——要扩展的模板的位置.
{% extends %}
actually takes a string - the location of the template to extend.
如果您想在 Python 中声明此变量,请使用您的字典将其传递给模板加载器.示例:
If you want to declare this variable in Python, pass it in to the template loader using your dictionary. Example:
import django.http
from django.shortcuts import render_to_response
# ...
INDEX_EXTEND = "index.html"
# ...
def response(request) :
return render_to_response("myview.html", {'extend': INDEX_EXTEND})
然后在视图中:
{% extends extend %}
请注意,'extend'
是在传递给模板的字典中传递的.您当然可以在 .py
文件中的任何其他位置定义变量 - 甚至在字典声明本身中.
Notice that 'extend'
was passed in the dictionary passed to the template. You can of course define the variable anywhere else in your .py
file - or even in the dictionary declaration itself.
记住 {% extends %}
也可以这样调用:
Remember that {% extends %}
can also be invoked as such:
{% extends "index.html" %}
查看关于模板继承,也是.
Check out the docs on Template inheritance, too.
这篇关于如何使用 Django 的模板扩展变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!