2011-12-10 25 views
1

我有,我需要设置在它的另一个嵌套模板变量标签模板变量在上下文(意见),并有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标签,而渲染?

回答

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, })) 

在你看来,与page作为呈现This is a test title for page {{ page.foo }}上下文。

如果您只使用从默认的上下文的东西,你可以写一个过滤器,使当前字符串与像{{ page.title|render }}这方面。但我不知道的方式从模板中得到整个范围内,因此这将仅适用于defeault上下文值工作。

编辑:发现了另一种方式,将新的答案。

1

您可以呈现在目前情况下的变量的模板标签。有关自定义模板标签的一般信息,请参阅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) 

你走了!您需要使用标签而不是普通变量或过滤器,但它会按照您所描述的内容进行操作。

+0

感谢马克!..这两种解决方案是有道理的。就我而言,第一个问题很容易解决。 – narxgun