django - 在 Django 中,是否有一种简单的方法可以在模板中将文本字段呈现为模板?

标签 django templates filter tags

您能想出一种在模板渲染期间将文本字段评估为模板的简单方法吗?

我知道如何在 View 中执行此操作,但我正在寻找模板 Filter 或 Tag ?

就像是:
{{ object.textfield|evaluate}}或者{% evaluate object.textfield %}
使用 object.textfield 包含以下内容:
a text with a {% TemplateTag %}.
其中TemplateTag将被评估,感谢 evaluate筛选。

最佳答案

这是解决我的问题的第一个标签实现:

from django import template

register = template.Library()

@register.tag(name="evaluate")
def do_evaluate(parser, token):
    """
    tag usage {% evaluate object.textfield %}
    """
    try:
        tag_name, variable = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError, "%r tag requires a single argument" % token.contents.split()[0]
    return EvaluateNode(variable)

class EvaluateNode(template.Node):
    def __init__(self, variable):
        self.variable = template.Variable(variable)

    def render(self, context):
        try:
            content = self.variable.resolve(context)
            t = template.Template(content)
            return t.render(context)
        except template.VariableDoesNotExist, template.TemplateSyntaxError:
            return 'Error rendering', self.variable

关于django - 在 Django 中,是否有一种简单的方法可以在模板中将文本字段呈现为模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1278042/

相关文章:

c++ - 来自不同命名空间的 friend 方法

python - 如何通过 __in 过滤另一个模型对象列表

ios - 过滤字符串数组,包括 "like"条件

python - django中自定义字段类保存在哪里?

python - celery django解释

django - 服务器 IP 地址应该在 ALLOWED_HOSTS django 设置中吗?

json - JQ 选择存在内键的对象

python - Django ORM 继承 : You are trying to add a non-nullable field 'dish_ptr' to [. ..] 没有默认值

c++ - 为什么 std::is_convertible_v 返回 true 即使此转换不合法?

c++ - 将常规函数绑定(bind)到 std::function