如何在传递给包含模板的参数中应用变量和过滤器?

时间:2013-04-06 20:44:25

标签: django django-templates

我有类似的html片段,我想作为一个单独的模板包括:

...
<div class='item'>
  <div class='header'>It's a header 1</div>
  <div class='text'>It's a text for paragraph 1.</div>
</div>

<div class='item'>
  <div class='header'>It's a header 2</div>
  <div class='text'>You have {{points}} point{{points|pluralize}}</div>
</div>
...

我制作了一个包含模板 item.html

<div class='item'>
  <div class='header'>{{header}}</div>
  <div class='text'>{{text}}</div>
</div>

将第一个片段替换为:

{% include "item.html" with title="It's a header 1" text="It's a text for paragraph 1." %}
{% include "item.html" with title="It's a header 2" text="You have {{points}} point{{points|pluralize}}" %}

如果我们使用'points'上下文变量以及如何应用变量'points'的值,如何应用过滤器'pluralize'?

现在我们输出You have {{points}} point{{points|pluralize}}

我可以没有自定义模板标签/过滤器吗?

更新

它可以是另一种方便的“DRY”方案(可能没有包含模板)。

分辨率

感谢karthikr的建议。我创建了下一个标签(解析)。它解析了变量的内容:

from django import template
from django.utils.safestring import mark_safe
from django.utils.html import escape

register = template.Library()
@register.tag( name="resolve" )

def do_resolve( parser, token ):
    nodelist = parser.parse(('endresolve',))

    parser.delete_first_token()

    return ResolveNode( nodelist )

class ResolveNode( template.Node ):
    def __init__( self, nodelist ):
        self.nodelist = nodelist

    def render( self, context ):
        output = self.nodelist.render( context ) # applye children here     
        output = template.Template( output ).render( context )
        return output

因此,我们可以使用标记

更改 item.html
<div class='item'>
  <div class='header'>{{header}}</div>
  <div class='text'>{% resolve %}{{text}}{% endresolve %}</div>
</div>

现在,如果我们以带有参数的字符串传递,它会正常处理。

1 个答案:

答案 0 :(得分:1)

这是一个想法:

在模板标记中,您可以解析{{}}的文本并解析上下文。

这可以让您了解呈现template tag nodes