2011-12-07 215 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