这将涉及到正则表达式。我不太擅长的东西,我写了一个例子,但你(或其他人)会(我保证)有一个更有效的方法来做到这一点。但是,这仅仅是一个例子:
from django.template import Library, Node, TemplateSyntaxError
from django.template import Template, Context
register = Library()
class TemplateEvalNode(Node):
def __init__(self, value):
self.value = Variable(value)
def render(self, context):
value = self.value.resolve(context)
regex = re.compile('{% \w+ %}')
# Grab the template tag (eg. {% TemplateTag %})
unevaluated_var = regex.search(value)
if unevaluated_var == None:
return value
# Create a template containing only the template tag
t = Template(unevaluated_var)
# Evaluate that template (with context)
return_var = t.render(Context(context))
# Return the original value with the template tag replaced with
# its actual value
return value.replace(unevaluated_var, return_var)
def template_eval(parser, token):
bits = token.contents.split()
if len(bits) != 2:
raise TemplateSyntaxError, "template_eval takes exactly one argument"
return TemplateEvalNode(bits[1])
template_eval = register.tag(template_eval)
我没有测试过这个呢,所以它可能无法正常工作直接关闭,但在理论上可以运行:
{% template_eval object.textfield %}
而且它会返回:
a text with a VALUE_OF_TEMPLATETAG.
预计会有更新,因为我现在要测试它并尝试解决任何问题,我的电池即将死亡,所以我现在发布这个测试。
同样期待更好的Python解决方案比我更聪明的解决方案:p。
编辑:好的,我太慢了,你打我!
感谢您的答复!对不起,快速响应;-) – 2009-08-14 15:30:55