您可以呈现在目前情况下的变量的模板标签。有关自定义模板标签的一般信息,请参阅https://docs.djangoproject.com/en/dev/howto/custom-template-tags/。
结果:
{% load renderme %}
{% renderme page.title %}
变为(为你提供的上下文):
This is a test title for page Test
模板标记代码(你将不得不提高开关输入检查,最主要的是它不但接受直接传递字符串):
from django import template
from django.template.context import Context
from django.template.base import Template
class RenderNode(template.Node):
def __init__(self, template_string_name = ''):
self.template_string_name = template_string_name
def render(self, context):
''' If a variable is passed, it is found as string, so first we use render to convert that
variable to a string, and then we render that string. '''
self.template_string = Template('{{ %s }}' % self.template_string_name).render(context)
return Template(self.template_string).render(context)
def render_me(parser, token):
try:
tag_name, template_string_name = token.split_contents()
except Exception:
raise template.TemplateSyntaxError('Syntax for renderme tag is wrong.')
return RenderNode(template_string_name)
register = template.Library()
register.tag('renderme', render_me)
你走了!您需要使用标签而不是普通变量或过滤器,但它会按照您所描述的内容进行操作。
感谢马克!..这两种解决方案是有道理的。就我而言,第一个问题很容易解决。 – narxgun