具有上下文变量参数的Django自定义模板标记

Ben*_*Ben 6 django django-templates django-models

我有一个自定义模板标签,显示日历.我想根据动态值填充日历上的某些项目.

这是标签:

@register.inclusion_tag("website/_calendar.html")
def calendar_table(post):
     post=int(post)
     imp=IMP.objects.filter(post__pk=post)
     if imp:
         ...do stuff
Run Code Online (Sandbox Code Playgroud)

在我的模板中,当我传递硬编码值时,它可以正常工作,例如

    {% load inclusion_tags %}

    {% calendar_table "6" %}
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试类似{%calendar_table"{{post.id}}"%}的内容时,会为int()尝试引发一个错误ValueError.我怎么能绕过这个?

Luk*_*ger 9

你想要{% calendar_table post.id %}; 额外的{{,}}是什么导致你胃灼热.

请注意,在自定义标记中,您需要"post.id"获取传递的字符串()并使用上下文解析它Variable.resolve.在Django文档中有更多关于它的信息; 特别是,请看这里:http://docs.djangoproject.com/en/1.3/howto/custom-template-tags/#passing-template-variables-to-the-tag