Ste*_*eve 4 django arguments templatetags
如果我创建了模板标记:
@register.simple_tag
def last_books(a_cat, cutoff=5):
objects = Books.objects.filter(category=a_cat)
return objects[:cutoff]
Run Code Online (Sandbox Code Playgroud)
我怎么能在我的模板中做这样的事情:
{% for book in last_books 'Sports' 3 %}
Run Code Online (Sandbox Code Playgroud)
我目前收到此错误:
'for'语句应使用'for y in y'格式:for last_books'Floys'3中的x
就个人而言,我只是通过视图将该书作为上下文变量传入.这样您就不需要模板标签了.
或者,您可以使用inclus_tag装饰器,这包含了将包含自定义上下文的包含模板呈现到当前文档中的想法.
但是如果你想继续当前的路径,那么simple_tag装饰者就没有办法了.当您需要将string要直接呈现的内容返回到模板中时,可以使用它.您要做的是设置模板上下文变量.这有点复杂,但并不太难.创建一个这样的节点:
class LastBooksNode(template.Node):
def __init__(self, category, cutoff=5, var_name='books'):
self.category = category
self.cutoff = cutoff
self.var_name = var_name
def render(self, context):
context[self.var_name] = Books.objects.filter(category=self.category)[:self.cutoff]
return ''
@register.tag(name='last_books')
def do_last_books(parser, token):
error = False
try:
tag_name, category, cutoff, _as, var_name = token.split_contents()
if _as != 'as':
error = True
except:
error = True
if error:
raise TemplateSyntaxError, 'last_books must be of the form, "last_books <category> <cutoff> as <var_name>"'
else:
return LastBooksNode(a_cat, cutoff, var_name)
Run Code Online (Sandbox Code Playgroud)
然后,您将使用以下命令调用模板标记:
{% import <your tag library> %}
{% last_books 'category' 5 as my_books %}
{% for book in my_books %}
....
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
未经测试,但我希望这表明了这个想法.如上所述,如果您不打算在多个位置重复使用,可以通过上下文或使用inclusion_tag将书籍直接传递到视图.
| 归档时间: |
|
| 查看次数: |
3780 次 |
| 最近记录: |