在Django中,在模板中有简单的方法来将文本字段渲染为模板吗? [英] In Django, is there an easy way to render a text field as a template, in a template?

查看:86
本文介绍了在Django中,在模板中有简单的方法来将文本字段渲染为模板吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我知道如何在视图中做到这一点, m寻找模板过滤器或标签?



某些东西:



{object.textfield | evaluate}}

{%evaluate object.textfield%}



与object.textfield包含以下内容:



带有{%TemplateTag%}的文本。 / code>



其中 TemplateTag 将被评估,感谢评估过滤器。

解决方案

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

 从django导入模板

register = template.Library()

@register。标签(name =评估)
def do_evaluate(解析器,令牌):

标签用法{%evaluate object.textfield%}

try:
tag_name,v ariable = token.split_contents()
除了ValueError:
raise template.TemplateSyntaxError,%r标签需要一个参数%token.contents.split()[0]
return EvaluateNode

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上下文)
除了template.VariableDoesNotExist,template.TemplateSyntaxError:
return'错误渲染',self.variable


Can you think of an easy way to evaluate a text field as a template during the template rendering.

I know how to do it in a view but I'm looking for a template Filter or a Tag ?

Something like:

{{ object.textfield|evaluate}} or {% evaluate object.textfield %}

with object.textfield containing something like:

a text with a {% TemplateTag %}.

In which TemplateTag will be evaluated, thanks to the evaluate filter.

解决方案

Here is a first Tag implementation to solve my question:

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中,在模板中有简单的方法来将文本字段渲染为模板吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆