自定义包含标签

时间:2011-12-07 09:06:15

标签: django django-templates

我想创建一个自定义包含标记(例如{% smart_include something %}),它会实现我们想要包含的内容,然后调用常规{% include %}标记。这应该是这样的:

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

有没有办法在python代码中使用{% include %}标签,以及具体如何?

UPD。退出,解决此问题的最佳方法就是使用render_to_string快捷方式

2 个答案:

答案 0 :(得分:0)

如果你查看 django.template.loader_tags ,你会找到一个函数 do_include ,它基本上是我们使用{%include%}时调用的函数。

所以你应该能够导入它在python中调用函数本身。

我没试过这个,但我认为它应该可行

答案 1 :(得分: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

最后,您可以复制include标记的功能。此代码段应指向正确的方向:

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
相关问题