2017-03-04 142 views
0

我已经定义了一个自定义标记函数,并试图将两个参数传入从我循环的数组派生的函数中。如何在模板标记中使用Django模板变量

本质上讲,我试图做一个类似于以下内容:

{% 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中有没有适当的方法来做到这一点?

+0

在你的第二次尝试,你已经忘了写{%ENDWITH%}。 –

+1

你检查过了吗? {%custom_tag_function forloop.counter数组|长度%} –

+0

工作,谢谢迈赫迪! – Marto

回答

0

正如在他的评论中指出的迈赫迪上面,下面的解决了这个问题:

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