django - 如何使用 Django 模板存储 templatetag 的结果?

标签 django django-templates

使用 Django 1.5.5,我需要调用自定义模板标签并以某种方式将结果存储在变量中,以检查它是否包含非空的空字符串。我需要看起来像这样的东西:

{% 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 %}

我的模板标签如下所示:

@register.simple_tag(takes_context=True)
def render_html(context, html):
    """Allows executing 'Django code' within the HTML"""
    return Template(html).render(context)

我还考虑过将自定义模板标签的返回值添加到上下文中。你怎么看待这件事?这会危险吗?这看起来像:

@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

最佳答案

如果标签是您控制的,那么也许可以考虑使用 assignment tag 。如果该标签不是您控制的,那么您可能必须使用您自己的分配标签将其包装起来。

关于django - 如何使用 Django 模板存储 templatetag 的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21456597/

相关文章:

django - 使用 L10N 为一种语言指定 Django 模板中的日期格式

python - Django:从元组中获取首选值

django - 注释在不存在的值上返回 null,我想将其转换为 null 为空字符串

python - Django Rest Framework 嵌套序列化器

django - 添加新子页面时的 wagtail pathoverflow

django - 在 Django 中使用 Gravatar

django - django <-> 应用程序服务器(node.js)之间的通信方法?

Django休息框架: How to set a field to null via PATCH request?

python - 我无法理解 django-markdownx 的用法

django - 获取模板中的第一个相关对象