【问题标题】:Django custom template tag passing variable number of argumentsDjango自定义模板标签传递可变数量的参数
【发布时间】:2011-10-12 14:43:54
【问题描述】:

我正在尝试编写一个 django 自定义模板标签,该标签将在模板中调用如下:

模板:

{% load tag_name %}
{% tag_fn arg1 arg2 ... arg n %}

arg1, ..., arg n 是 python 变量。

模板标签:

在模板标签中我有四个字典

d1 = {"key1": "some text" + str(arg2), "key2":" some text" + str(arg m) 我有四个字典。

根据arg1 的值,应呈现相应的字典,我希望模板标签将"some text value(arg1) some text value(arg m)" 作为结果返回到模板。

请提出一种实现方法。

【问题讨论】:

标签: django django-templates


【解决方案1】:

您可以使用 Python 内置的从列表中传入多个值的方式将任意数量的变量传递给自定义模板标签。示例:

from django import template

register = template.Library()

@register.tag('my_tag')
def do_whatever(parser, token):
    bits = token.contents.split()
    """
    Pass all of the arguments defined in the template tag except the first one,
    which will be the name of the template tag itself.
    Example: {% do_whatever arg1 arg2 arg3 %}
    *bits[1:] would be: [arg1, arg2, arg3]
    """
    return MyTemplateNode(*bits[1:])

class MyTemplateNode(template.Node):
    def __init__(self, *args, **kwargs):
        do_something()

    def render(self, context):
        do_something_else()

希望对你有所帮助。

【讨论】:

    【解决方案2】:

    实现这一点的最简单方法是使用 Python 接受可变数量 args 的常规方式:

    @register.simple_tag()
    def my_tag(*args):
      # do stuff with args, which is a list of all the arguments
      return 'what you want to output'
    

    然后你就可以随心所欲地使用它了:

    {% my_tag arg1 arg2 arg3 %}
    

    【讨论】:

      猜你喜欢
      • 2021-09-04
      • 2014-03-04
      • 1970-01-01
      • 2011-06-17
      • 2014-07-14
      • 2011-08-27
      • 2023-03-24
      • 1970-01-01
      • 2021-02-15
      相关资源
      最近更新 更多