Django:带有2个变量的自定义模板标签

Django: custom template tag which takes 2 variables

我想要一个将两个变量作为参数的自定义模板标签。这是我的模板中的内容:

{% load accountSum %}
{% accountSum 'account_id' 'account_type' %}

我了解到您需要加载这些变量的上下文,但我还没有找到可行的方法。所以我的问题是,如何在 templatetags/accountSum.py?

中定义自定义模板标签

这是我目前拥有的:

from django import template

register = template.Library()

def accountSum(context, account_id, account_type):
    account_id = context[account_id]
    account_type = context[account_type]
    # do something with the data
    # return the modified data

register.simple_tag(takes_context=True)(accountSum)

你误解了模板标签的用法,I have read that you need to load the context of these variables... context 只有当你需要 access/modify 现有上下文时才需要,而不是如果您只需要 return 根据提供的参数计算出的值。

因此,在您的情况下,您只需要:

@register.simple_tag
def accountSum(account_id, account_type):
   # your calculation here...
   return # your return value here

Django 文档有更详细的解释和示例,您可以按照 -- Simple tags

或者,如果您打算采用 上下文account_idaccount_type 和 return 每次调用的修改值,您可以简单地省略 参数 ,只需执行以下操作:

@register.simple_tag(take_context=True)
def accountSum(context):
    account_id = context['account_id']
    account_type = context['account_type']
    # do your calculation here...
    return # your modified value

然后您只需在模板中调用 {% accountSum %}

或者,如果您想动态地将上下文内容作为参数:

@register.simple_tag(take_context=True)
def accountSum(context, arg1, arg2):
    arg1 = context[arg1]
    arg2 = context[arg2]
    # calculation here...
    return # modified value...

并使用 string 在模板中传递参数,例如:

{% accountSum 'account_id' 'account_type' %}

我希望这能帮助您了解如何在您的案例中使用模板标签。

已更新

我的意思是这个(因为你不需要访问上下文,你真正需要的是像往常一样接受参数):

@register.simple_tag
def accountSum(arg1, arg2):
   # your calculation here...
   return # your return value here

并在您的模板中使用它:

{% accountSum account.account_id account.account_type %}