如何在模板代码中设置一个variables的值?

说我有一个模板

<html> <div>Hello {{name}}!</div> </html> 

在testing它的时候,定义variables的值而不用触及调用这个模板的python代码会很有用。 所以我正在寻找这样的东西

 {% set name="World" %} <html> <div>Hello {{name}}!</div> </html> 

在Django中是否存在这样的事情?

你可能需要带模板标签。

 {% with "World" as name %} <html> <div>Hello {{name}}!</div> </html> {% endwith %} 

编辑

现在使用with标签的正确方法是:(旧格式仍然受支持)

 {% with name="World" greeting="Hello" %} <html> <div>{{ greeting }} {{name}}!</div> </html> {% endwith %} 

另一种不需要将所有内容都放在“with”块中的方法是创build一个自定义标签,在上下文中添加一个新variables。 如:

 class SetVarNode(template.Node): def __init__(self, new_val, var_name): self.new_val = new_val self.var_name = var_name def render(self, context): context[self.var_name] = self.new_val return '' import re @register.tag def setvar(parser,token): # This version uses a regular expression to parse tag contents. try: # Splitting by None == splitting by spaces. tag_name, arg = token.contents.split(None, 1) except ValueError: raise template.TemplateSyntaxError, "%r tag requires arguments" % token.contents.split()[0] m = re.search(r'(.*?) as (\w+)', arg) if not m: raise template.TemplateSyntaxError, "%r tag had invalid arguments" % tag_name new_val, var_name = m.groups() if not (new_val[0] == new_val[-1] and new_val[0] in ('"', "'")): raise template.TemplateSyntaxError, "%r tag's argument should be in quotes" % tag_name return SetVarNode(new_val[1:-1], var_name) 

这将允许你在你的模板中写下这样的内容:

 {% setvar "a string" as new_template_var %} 

请注意,这大部分是从这里拿走的

有一些像约翰描述的那样的技巧; 然而,Django的devise模板语言不支持设置variables(请参阅Django文档中的“Philosophy”框中的模板 )。
因此,改变任何variables的推荐方法通过触摸Python代码。

在你的模板标签中,你可以添加一个这样的标签:

 from django import template register = template.Library() @register.assignment_tag def define(val=None): return val 

然后在你的模板中,你可以像下面这样为上下文赋值:

 {% if item %} {% define "Edit" as action %} {% else %} {% define "Create" as action %} {% endif %} Would you like to {{action}} this item 

最好的解决scheme是编写一个自定义的assignment_tag 。 这个解决scheme比使用with标签更干净with因为它实现了逻辑和样式之间非常明确的分离。

首先创build一个模板标签文件(例如appname/templatetags/hello_world.py ):

 from django import template register = template.Library() @register.assignment_tag def get_addressee(): return "World" 

现在,您可以在模板中使用get_addressee模板标签:

 {% load hello_world %} {% get_addressee as addressee %} <html> <body> <h1>hello {{addressee}}</h1> </body> </html> 

一般来说这不是一个好主意。 在Python中执行所有的逻辑,并将数据传递给模板进行显示。 模板应该尽可能简单,以确保在devise上工作的人可以专注于devise而不是担心逻辑。

举一个例子,如果你需要模板中的派生信息,最好把它放到python代码中的一个variables中,然后把它传递给模板。

也许default模板filter不是2009年的选项…

 <html> <div>Hello {{name|default:"World"}}!</div> </html> 

在你的模板中,你可以这样做:

 {% jump_link as name %} {% for obj in name %} <div>{{obj.helo}} - {{obj.how}}</div> {% endfor %} 

在你的模板标签中,你可以添加一个这样的标签:

 @register.assignment_tag def jump_link(): listArr = [] for i in range(5): listArr.append({"helo" : i,"how" : i}) return listArr 

使用with语句 。

 {% with total=business.employees.count %} {{ total }} employee{{ total|pluralize }} {% endwith %} 

我不能在这个答案的第一段暗示代码。 也许模板语言已经废弃了旧的格式。