2011-09-28 70 views
1

我们已经得到了第三方的Django模板标签是这样的:我们每次使用的时间如何让Django模板标签,它扩展到另一个(宏)

{% frobnicate "foo", "bar", "baz" %} 
    do stuff with {{ frobnicator }} 
{% endfrobnicate %} 

不幸的是,do stuff with {{ frobnicator }}部分重复{% frobnicate %}标记。

什么是建立一个标记,以便像

{% frobnicate2 "foo", "bar", "baz" %} 

...扩展到第一个例子最简单的方法?

更新:简单的包含标签是不够的。我没有在上面的例子中说清楚,但我需要能够操纵传递给扩展的参数。

+2

你的意思是[包含模板标签](https://docs.djangoproject.com/en/1.3/howto/custom-template-tags/#inclusion-tags) –

+0

@DanielRoseman也许吧?我不确定他们是否可以在这里做我想做的事。我会重新阅读文档。 –

+0

@DanielRoseman更新的问题... –

回答

2

创建一个模板过滤器,它将呈现您的custom string instead of a template file

声明像这样(此代码测试)

#app_name/templatetags/frobnicative_tags.py 
from django.template import Template, Context 
register = Library() 

@register.tag(name = 'frobnicate2') 
def frobnicate2(parser, token): 
    args = token.split_contents() 
    template_string = """ 
     {%% load my-third-party-frobnicator-lib %%} 
     {%% frobnicate %s %%} 
      do stuff with {{ frobnicator }} 
     {%% endfrobnicate %%} 
    """ 
    return Frobnicate2(''.join(args[1:]), template_string) 

class Frobnicate2(template.Node): 
    def __init__(self, frobnicative_args, template_string): 
     self.template_string = template_string 
     self.args = frobnicative_args 

    def render(self, context): 
     """ 
     Dict inside a Context() is empty because we 
     need to pass a context in order to render, even if 
     the context is empty. 
     """ 
     return Template(self.template_string % self.args).render(Context({})) 

不要忘记,以取代 “我-第三方frobnicator-lib的” 同一个名字您正在加载的实际第三方库。

然后,您可以使用{% frobnicate2 "foo", "bar", "baz" %}就像您想要的那样渲染整个通话方标签序列。

+1

宾果,我认为这是我需要的。谢谢! –

+0

@付费书呆子,我刚刚在我的答案中修复了两个小错误。 –