使用Django 1.5.5我需要调用一个自定义的模板标签,并以某种方式将结果存储在一个变量中,以检查它是否包含非空的空字符串。我需要的东西,应该是这样的:内置templatetag允许调用它使用语法存放在变量的结果如何使用Django模板存储模板标签的结果?
{% load smart_html %}
{% render_html widget.content as widget_content %}
{% if widget_content %}
Do stuff here...
{% endif %}
这是在{%URL%}启发:
{% url 'named_url' as my_named_url %}
我templatetag样子:
@register.simple_tag(takes_context=True)
def render_html(context, html):
"""Allows executing 'Django code' within the HTML"""
return Template(html).render(context)
我也想过从定制templatetag上下文将返回值。你怎么看待这件事?这会危险吗?这看起来像:
@register.simple_tag(takes_context=True)
def render_html(context, html, var_name=None):
"""Allows executing 'Django code' within the HTML"""
html = Template(html).render(context)
if var_name:
context[var_name] = html
html = ''
return html
感谢您的快速响应!这似乎是我需要的。但是,我还需要'as foo'作为可选项,因为它位于'{%url%}'模板标签上。我更新了我的问题,只有在设置了'var_name'的情况下,才使用修改过的templatetag将值分配给上下文。你有什么想法如何使用'assignment tag'来做到这一点?谢谢! – Caumons