简体   繁体   English

如何在模板标签中使用Django模板变量

[英]How to use Django template variables in template tags

I've defined a custom tag function and am trying to pass two arguments into the function that are derived from the array I'm looping through. 我定义了一个自定义标记函数,并试图将两个参数传递给该函数,这些参数是从我正在遍历的数组派生的。

Essentially, I'm trying to do something akin to the following: 本质上,我正在尝试执行以下操作:

{% for x in array %}
  {% custom_tag_function {{ forloop.counter }} {{ array|length }} %}
{% endfor %}

However I'm receiving a parsing error as django is passing in the argument as a string (eg "{{ forloop.counter }}" ) instead of the evaluated value. 但是,由于django将参数作为字符串(例如"{{ forloop.counter }}" )而不是评估值传递给我,因此我收到了解析错误。

I tried to do this: 我试图这样做:

{% for x in array %}
  {% with cnt={{ forloop.counter }} len={{ array|length }} %}
    {% custom_tag_function cnt len %}
{% endfor %}

But I receive the same parsing error. 但是我收到同样的解析错误。

Is there a proper way to do this within django? 在Django中是否有适当的方法可以做到这一点?

As noted by Mehdi in his comment above, the following solves the problem: 正如Mehdi在上面的评论中所指出的,以下解决了该问题:

{% for x in array %}
  {% custom_tag_function forloop.counter array|length %}
{% endfor %}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM