【发布时间】:2014-07-04 04:00:53
【问题描述】:
这是我与上下文变量交互的第一个模板标签。所以我可能做错了什么。
我想为一个对象传递一个 PK。所以,是这样的:
{% get_checkbox with object.id %}
这将使用object.id 来获取该对象。如果存在则呈现一些 HTML,如果不存在则呈现不同的 HTML。我这样做是作为一个模板标签,因为一旦我有了记录,我就会做更多的高级过滤。但我需要先获取上下文变量。
然后在模板标签中我想做这样的事情:
from django import template
from project.app.models import Model
register = template.Library()
class ModelNode(template.Node):
def __init__(self, object_id):
self.object_id = template.Variable(object_id)
def render(self, context):
o_id = self.object_id.resolve(self.object_id)
obj = Model.objects.get(id=o_id)
if obj:
return '<h3>Not yet</h3>'
else:
return '<h3>Go ahead</h3>'
@register.tag
def get_checkbox(parser, token):
"""
Usage::
{% get_checkbox with [object_id] %}
"""
bits = token.contents.split()
tag_name = bits[0]
if len(bits) != 3:
raise template.TemplateSyntaxError, "%s tag takes exactly two arguments" % (tag_name)
if bits[1] != 'with':
raise template.TemplateSyntaxError, "second argument to the %s tag must be 'with'" % (tag_name)
object_id = bits[2]
return ModelNode(object_id)
但我收到以下错误:
VariableDoesNotExist at /app/
Failed lookup for key [object] in u'object.id'
好像没有在模板标签中解析变量?
我很乐意提出建议和更正。感谢您的宝贵时间。
【问题讨论】:
-
object在您的模板上下文中吗? -
是的,
object在模板上下文中。