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

时间:2017-03-04 16:33:00

标签: python django jinja2

我已经定义了一个自定义标记函数,并试图将两个参数传递给函数,这些参数是从我循环的数组派生的。

基本上,我正在尝试做类似以下的事情:

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

但是我收到解析错误,因为django将参数作为字符串(例如"{{ forloop.counter }}")而不是评估值传递。

我试着这样做:

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

但是我收到了同样的解析错误。

在django中有没有正确的方法呢?

1 个答案:

答案 0 :(得分:0)

正如Mehdi在上面的评论中指出的那样,以下问题解决了这个问题:

{% for x in array %}
  {% custom_tag_function forloop.counter array|length %}
{% endfor %}
相关问题