How to set a value of a variable inside a template code?

后端 未结 9 1255
我寻月下人不归
我寻月下人不归 2020-11-27 09:55

Say I have a template


Hello {{name}}!

While testing it, it would be useful to define the

9条回答
  •  孤城傲影
    2020-11-27 10:29

    An alternative way that doesn't require that you put everything in the "with" block is to create a custom tag that adds a new variable to the context. As in:

    class SetVarNode(template.Node):
        def __init__(self, new_val, var_name):
            self.new_val = new_val
            self.var_name = var_name
        def render(self, context):
            context[self.var_name] = self.new_val
            return ''
    
    import re
    @register.tag
    def setvar(parser,token):
        # This version uses a regular expression to parse tag contents.
        try:
            # Splitting by None == splitting by spaces.
            tag_name, arg = token.contents.split(None, 1)
        except ValueError:
            raise template.TemplateSyntaxError, "%r tag requires arguments" % token.contents.split()[0]
        m = re.search(r'(.*?) as (\w+)', arg)
        if not m:
            raise template.TemplateSyntaxError, "%r tag had invalid arguments" % tag_name
        new_val, var_name = m.groups()
        if not (new_val[0] == new_val[-1] and new_val[0] in ('"', "'")):
            raise template.TemplateSyntaxError, "%r tag's argument should be in quotes" % tag_name
        return SetVarNode(new_val[1:-1], var_name)
    

    This will allow you to write something like this in your template:

    {% setvar "a string" as new_template_var %}
    

    Note that most of this was taken from here

提交回复
热议问题