【问题标题】:Nested template tags from context来自上下文的嵌套模板标签
【发布时间】:2011-12-10 23:29:18
【问题描述】:

我有一个案例,我需要在上下文(视图)中设置一个带有另一个嵌套模板变量标签的模板变量,并使用 django 模板机制来解析标签和嵌套标签。

在我看来:

page['title'] = 'This is a test title for page {{ page.foo }}'
page['foo']   = 'Test'
...
render_to_response('x.html', {'page':page})

在模板中我有:

<html>
....
<title>{{page.title}}</title>
...</html>

如何让page.title 在渲染时也解析嵌入的page.foo 标记?

【问题讨论】:

    标签: django django-templates django-views


    【解决方案1】:

    我不知道有什么方法可以做到这一点,如果默认情况下没有实现它也不会感到惊讶,因为 Django 将不再能够一次性渲染所有内容......

    这里有一些事情有点接近,也许它会有所帮助。

    最简单:只需使用 Python %s 在您的视图中进行操作

    page['title'] = 'This is a test title for page %s' % page['foo']
    

    如果你想使用 Django 渲染:

    page['title'] = Template(page['title']).render(Context({'page': page, }))
    

    在您看来,这会将This is a test title for page {{ page.foo }} 与page 作为上下文。

    如果您只使用默认上下文中的内容,则可以编写一个过滤器,使用该上下文呈现当前字符串,例如{{ page.title|render }}。但我不知道有一种方法可以从模板中获取整个上下文,因此这只适用于默认上下文值。

    编辑:找到另一种方式,将做出新的答案。

    【讨论】:

      【解决方案2】:

      您可以制作一个在当前上下文中呈现变量的模板标签。有关自定义模板标签的一般信息,请参阅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)
      

      给你!您将需要使用标签而不是普通变量或过滤器,但它会按照您的描述进行。

      【讨论】:

      • 谢谢马克!.. 这两种解决方案都有意义。就我而言,第一个很容易解决问题。
      猜你喜欢
      • 2011-12-15
      • 1970-01-01
      • 2012-07-09
      • 1970-01-01
      • 2011-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多