Django simple_tag 和设置上下文变量 [英] Django simple_tag and setting context variables

查看:16
本文介绍了Django simple_tag 和设置上下文变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 simple_tag 并设置上下文变量.我正在使用 django 的主干版本

Im trying to use a simple_tag and set a context variable. i am using the trunk version of django

from django import template

@register.simple_tag(takes_context=True)
def somefunction(context, obj):   
    return set_context_vars(obj)

class set_context_vars(template.Node):
    def __init__(self, obj):
        self.object = obj

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

这不会设置变量,但是如果我用 @register.tag 做一些非常相似的事情,它可以工作,但对象参数不会通过...

This doesnt set the variable, but if I do something very similar with @register.tag it works but the object parameter doesn't pass through...

谢谢!

推荐答案

你在这里混合了两种方法.simple_tag 只是一个辅助函数,它减少了一些样板代码并应该返回一个字符串.要设置上下文变量,您需要(至少使用普通 django)用render方法编写自己的标签.

You are mixing two approaches here. A simple_tag is merely a helper function, which cuts down on some boilerplate code and is supposed to return a string. To set context variables, you need (at least with plain django) to write your own tag with a render method.

from django import template

register = template.Library()


class FooNode(template.Node):

    def __init__(self, obj):
        # saves the passed obj parameter for later use
        # this is a template.Variable, because that way it can be resolved
        # against the current context in the render method
        self.object = template.Variable(obj)

    def render(self, context):
        # resolve allows the obj to be a variable name, otherwise everything
        # is a string
        obj = self.object.resolve(context)
        # obj now is the object you passed the tag

        context['var'] = 'somevar'
        return ''


@register.tag
def do_foo(parser, token):
    # token is the string extracted from the template, e.g. "do_foo my_object"
    # it will be splitted, and the second argument will be passed to a new
    # constructed FooNode
    try:
        tag_name, obj = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError, "%r tag requires exactly one argument" % token.contents.split()[0]
    return FooNode(obj)

这可以这样调用:

{% do_foo my_object %}
{% do_foo 25 %}

这篇关于Django simple_tag 和设置上下文变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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