django assignment_tag 赋值标签

  • 2020 年 3 月 17 日
  • 筆記

赋值标签(保存模板变量的值)

django.template.Library.assignment_tag()

为了简单化设置上下文中变量的标签的创建,Django 提供一个辅助函数assignment_tag。这个函数方式的工作方式与simple_tag 相同,不同之处在于它将标签的结果存储在指定的上下文变量中而不是直接将其输出。

我们之前的current_time 函数从而可以这样写︰

@register.assignment_tag  def get_current_time(format_string):      return datetime.datetime.now().strftime(format_string)

然后你可以使用as 参数后面跟随变量的名称将结果存储在模板变量中,并将它输出到你觉得合适的地方︰

{% get_current_time "%Y-%m-%d %I:%M %p" as the_time %}  <p>The time is {{ the_time }}.</p>

如果你的模板标签需要访问当前上下文,你可以在注册标签时使用takes_context 参数:

@register.assignment_tag(takes_context=True)  def get_current_time(context, format_string):      timezone = context['timezone']      return your_get_current_time_method(timezone, format_string)

注意函数的第一个参数必须叫做context。

takes_context 选项的工作方式的详细信息,请参阅包含标签

assignment_tag 函数可以接受任意数量的位置参数和关键字参数。例如:

@register.assignment_tag  def my_tag(a, b, *args, **kwargs):      warning = kwargs['warning']      profile = kwargs['profile']      ...      return ...

然后在模板中,可以将任意数量的由空格分隔的参数传递给模板标签。像在Python 中一样,关键字参数的值的设置使用等号("=") ,并且必须在位置参数之后提供。例子:

{% my_tag 123 "abcd" book.title warning=message|lower profile=user.profile as the_result %}

搬运地址:https://yiyibooks.cn/__trs__/xx/django_182/howto/custom-template-tags.html

标签: DJANGO