2024-10-01 02:32:52 发布
网友
我想要一个自定义模板标记,它以两个变量作为参数。以下是我在模板中的内容:
{% load accountSum %} {% accountSum 'account_id' 'account_type' %}
我已经读到你需要加载这些变量的上下文,但是我还没有找到一个有效的方法。所以我的问题是,如何在templatetags中定义自定义模板标记/accountSum.py?在
到目前为止,我得到的是:
您误解了模板标记的用法,I have read that you need to load the context of these variables。。。只有当您需要访问/修改现有上下文时,才需要上下文,而不是只需要从提供的参数返回计算值。在
I have read that you need to load the context of these variables
所以,在你的情况下,你只需要:
@register.simple_tag def accountSum(account_id, account_type): # your calculation here... return # your return value here
Django文档有更详细的解释和示例,您可以按照Simple tags
或者,如果您的意图是使用上下文值帐户id和帐户类型并在每次调用时返回一个修改后的值,则可以忽略使用参数,只需执行以下操作:
然后您只需在模板中调用{% accountSum %}。在
{% accountSum %}
或者,如果要动态地将上下文内容作为参数:
@register.simple_tag(take_context=True) def accountSum(context, arg1, arg2): arg1 = context[arg1] arg2 = context[arg2] # calculation here... return # modified value...
并使用字符串在模板中传递参数,如:
{% 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 %}
您误解了模板标记的用法,
I have read that you need to load the context of these variables
。。。只有当您需要访问/修改现有上下文时,才需要上下文,而不是只需要从提供的参数返回计算值。在所以,在你的情况下,你只需要:
Django文档有更详细的解释和示例,您可以按照Simple tags
或者,如果您的意图是使用上下文值帐户id和帐户类型并在每次调用时返回一个修改后的值,则可以忽略使用参数,只需执行以下操作:
^{pr2}$然后您只需在模板中调用
{% accountSum %}
。在或者,如果要动态地将上下文内容作为参数:
并使用字符串在模板中传递参数,如:
{% accountSum 'account_id' 'account_type' %}
我希望这能帮助您理解如何在您的案例中使用模板标记。在
更新
我的意思是这样的(因为你不需要访问上下文,你真正需要的是像平常一样进行辩论):
并在模板中使用:
{% accountSum account.account_id account.account_type %}
相关问题 更多 >
编程相关推荐