我将使用自定义模板标记。它使得设置上下文变量非常容易
#yourapp/templatetags/business_tags.py
from django import template
register = template.Library()
class BusinessNode(template.Node):
def __init__(self, instance, varName):
self.instance, self.varName=instance, varName
def render(self, context):
instance=template.Variable(self.instance).render(context)
if instance.passes_some_test():
context[self.varName]='Some message'
else:
context[self.varName]="Some other message"
return ''
@register.tag
def business_check(parser, token):
bits=token.split_contents()
if len(bits)==5:
return BusinessNode(bits[2],bits[4])
return ''
然后在模板中
{% load business_tags %}
{% business_check for someVar as myMessage %}
{{myMessage}}
这对于将其他类型的数据插入到上下文中同样有效。