是否有 Django 模板标签可以让我设置上下文变量? [英] Is there a Django template tag that lets me set a context variable?

查看:18
本文介绍了是否有 Django 模板标签可以让我设置上下文变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够将模板中的变量设置为字符串值.我写了一个标签,但它似乎没有改变上下文.预期用途是:

I want to be able to set variables in a template to string values. I wrote a tag, but it doesn't seem to change the context. The intended use is:

{% define "a string" as my_var %}

更新(已解决):

class DefineNode(Node):
    def __init__(self, var, name):
        self.var = var
        self.name = name

    def __repr__(self):
        return "<DefineNode>"

    def render(self, context):
        context[self.name] = self.var
        return ''

@register.tag
def define(parser, token):
    """
    Adds a name to the context for referencing an arbitrarily defined string.

    For example:

        {% define "my_string" as my_string %}

    Now anywhere in the template:

        {{ my_string }}
    """
    bits = list(token.split_contents())
    if (len(bits) != 4 or bits[2] != "as") or 
        not (bits[1][0] in ('"', "'") and bits[1][-1] == bits[1][0]):
        raise TemplateSyntaxError("%r expected format is '"string" as name'" % bits[0])
    else:
        value = bits[1][1:-1]
    name = bits[3]
    return DefineNode(value, name)

推荐答案

您无需编写自己的标签.内置的 {% with %} 标签就是这样做的.

You don't need to write your own tag. The built-in {% with %} tag does this.

这篇关于是否有 Django 模板标签可以让我设置上下文变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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