我如何使用Django的模板扩展变量?

时间:2021-11-03 06:13:36

The django template doc mentions the following for extending templates:

django模板doc提到了以下扩展模板:

{% extends variable %}

Where do I define the variable? Is it from the views.py?

我在哪里定义变量?是来自views.py吗?

2 个解决方案

#1


16  

{% extends %} actually takes a string - the location of the template to extend.

{%extends%}实际上需要一个字符串 - 要扩展的模板的位置。

If you want to declare this variable in Python, pass it in to the template loader using your dictionary. Example:

如果要在Python中声明此变量,请使用字典将其传递给模板加载器。例:

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})

And then in the view:

然后在视图中:

{% extends extend %}

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.

请注意,'extend'是在传递给模板的字典中传递的。您当然可以在.py文件中的任何其他位置定义变量 - 甚至可以在字典声明本身中定义变量。

Remember that {% extends %} can also be invoked as such:

请记住,{%extends%}也可以这样调用:

{% extends "index.html" %}

Check out the docs on Template inheritance, too.

查看有关模板继承的文档。

#2


6  

Yes, it's just a context variable like any other.

是的,它只是一个像其他任何一样的上下文变量。

You don't need to use a variable - {% extends "main.html" %} is perfectly acceptable, in fact preferable unless you need to do something massively dynamic with template inheritance.

您不需要使用变量 - {%extends“main.html”%}是完全可以接受的,实际上除非您需要使用模板继承进行大规模动态操作,否则更可取。

#1


16  

{% extends %} actually takes a string - the location of the template to extend.

{%extends%}实际上需要一个字符串 - 要扩展的模板的位置。

If you want to declare this variable in Python, pass it in to the template loader using your dictionary. Example:

如果要在Python中声明此变量,请使用字典将其传递给模板加载器。例:

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})

And then in the view:

然后在视图中:

{% extends extend %}

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.

请注意,'extend'是在传递给模板的字典中传递的。您当然可以在.py文件中的任何其他位置定义变量 - 甚至可以在字典声明本身中定义变量。

Remember that {% extends %} can also be invoked as such:

请记住,{%extends%}也可以这样调用:

{% extends "index.html" %}

Check out the docs on Template inheritance, too.

查看有关模板继承的文档。

#2


6  

Yes, it's just a context variable like any other.

是的,它只是一个像其他任何一样的上下文变量。

You don't need to use a variable - {% extends "main.html" %} is perfectly acceptable, in fact preferable unless you need to do something massively dynamic with template inheritance.

您不需要使用变量 - {%extends“main.html”%}是完全可以接受的,实际上除非您需要使用模板继承进行大规模动态操作,否则更可取。