Django simple_tag和设置上下文变量

ffvjumwh  于 2023-05-19  发布在  Go
关注(0)|答案(3)|浏览(95)

我尝试使用simple_tag并设置一个上下文变量。我使用的是django的 Backbone.js 版本:

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做一些非常类似的事情,它可以工作,但是object参数不会通过...
谢谢!

xggvc2p6

xggvc2p61#

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

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 %}
6jygbczu

6jygbczu2#

从Django 1.9开始,可以通过使用as参数后跟变量名来将simple_tag结果存储在模板变量中:

@register.simple_tag
def current_time(format_string):
    return datetime.datetime.now().strftime(format_string)
{% current_time "%Y-%m-%d %I:%M %p" as the_time %}
<p>The time is {{ the_time }}.</p>
xeufq47z

xeufq47z3#

您可以使用@register.simple_tag存储一个上下文变量,它返回简单的数据,而不是返回一个复杂的基于Node类的对象,如下所示:

# "custom_tags.py"

from django.template import Library

register = Library()

@register.simple_tag(takes_context=True)
def person(context):
    context["name"] = "John"
    context["age"] = 36
    return ""
# "index.html"

{% load custom_tags %}

{% person %}
{{ name }} {{ age }}

输出:

John 36

此外,您可以使用as参数将@register.simple_tagperson()的返回值存储到person_info,如下所示:

# "custom_tags.py"

@register.simple_tag(takes_context=True)
def person(context):
    return "John 36"
# "index.html"

{% load custom_tags %}

{% person as person_info %}
{{ person_info }}

输出:

John 36

并且,您可以使用@register.tag存储上下文变量,它返回一个复杂的基于Node(类)的对象,如下所示。* @register.tag不能接受takes_context参数,否则会出现错误,并且无法使用as参数:

# "custom_tags.py"

from django.template import Library, Node

register = Library()

@register.tag
def person(parser, token):
    return PersonNode()

class PersonNode(Node):
    def __init__(self):
        pass

    def render(self, context):
        context["name"] = "John"
        context["age"] = 36
        return ""
# "index.html"

{% load custom_tags %}

{% person %}
{{ name }} {{ age }}

输出:

John 36

相关问题