2011-12-07 218 views
0

我想制作一个自定义包含标签(如{% smart_include something %}),它实现了我们想要包含的事物,然后调用常规{% include %}标签。这应该是这样的:自定义包含标签

@register.simple_tag 
def smart_include(something): 
    if something == "post": 
      template_name = "post.html" 
      return regular_include_tag(template_name) 

是否有使用{% include %}标签在Python代码的方式,以及究竟如何?

UPD。回合的出来,要解决这个问题,只是使用render_to_string快捷

回答

0

如果你看看django.template.loader_tags您填写找到一个函数do_include这基本上是叫我们当函数的最好方法使用{%include%}。

所以你应该可以导入它在Python中调用函数本身。

我还没有试过,但我认为它应该工作

+1

我应该作为'parser'参数发送给这个函数吗? – nukl

0

我想是有原因的,为什么你不这样做:

{% if foo %} 
    {% include 'hello.html' %} 
{% endif %} 

如果something是一个定数,你可以使用inclusion tags。在您的模板,而不是{% smart_tag something %},你有{% something %},那么你的标签库是这样的:

@register.inclusion_tag('post.html') 
def something(): 
    return {} # return an empty dict 

最后,您可以复制包括标签的功能。这段代码应该指向你正确的方向:

filepath = '/full/path/to/your/template/%s' % something 
try: 
    fp = open(filepath, 'r') 
    output = fp.read() 
    fp.close() 
except IOError: 
    output = '' 
try: 
    t = Template(output, name=filepath) 
    return t.render(context) 
except TemplateSyntaxError, e: 
    return '' # Fail silently. 
return output