更新时间:2023-11-30 14:51:28
您使用 dot-operator 索引数组,或者,真的做任何事情。
技术上,当模板系统
遇到一个点时,它按照以下顺序尝试
以下查找:*字典查找
/ pre>
*属性查找
*方法调用
*列表索引查找
我不相信你可以在索引上做数学。你必须以其他方式传递你的数组,这样你就不需要这样做了。
I am writing a template for my first django website.
I am passing a list of dictionaries to the template in a variable. I also need to pass a few other lists which hold boolean flags. (Note: all lists have the same length)
The template looks something like this:
<html>
<head><title>First page</title></head><body>
{% for item in data_tables %}
<table>
<tbody>
<tr><td colspan="15">
{% if level_one_flags[forloop.counter-1] %}
<tr><td>Premier League
{% endif %}
<tr><td>Junior league
<tr><td>Member count
{% if level_two_flags[forloop.counter-1] %}
<tr><td>Ashtano League
{% endif %}
</tbody>
</table>
{% endfor %}
</body>
</html>
I am getting the following error:
Template error
In template /mytemplate.html, error at line 7 Could not parse the remainder: '[forloop.counter-1]' from 'level_one_flags[forloop.counter-1]'
I am, not suprised I am getting this error, since I was just trying to see if would work. So far, from the documentation, I have not found out how to obtain the items in a list by index (i.e. other than by enumeration).
Does anyone know how I may access a list by index in a template?
You use the dot-operator to index the array, or, really, to do anything.
Technically, when the template system encounters a dot, it tries the following lookups, in this order:
* Dictionary lookup * Attribute lookup * Method call * List-index lookup
I don't believe you can do math on the index. You'll have to pass in your array constructed in some other way so that you don't have to do this subtraction.