在Django模板中构建一个列表

时间:2010-12-09 05:41:55

标签: django django-templates

使用此代码:

{% for o in [1,2,3] %}
    <div class="{% cycle 'row1' 'row2' %}">
        {% cycle 'row1' 'row2' %}
    </div>
{% endfor %}

我得到TemplateSyntaxError

Could not parse the remainder: '[1,2,3]' from '[1,2,3]'

有没有办法在模板中构建列表?

7 个答案:

答案 0 :(得分:54)

我们可以在str对象上使用split方法:

page.html:

{% with '1 2 3' as list %}
  {% for i in list.split %}
    {{ i }}<br>
  {% endfor %}
{% endwith %}

结果:

1
2
3

答案 1 :(得分:25)

你可以通过狡猾地使用make_list过滤器来做到这一点,但这可能是一个坏主意:

{% for o in "123"|make_list %}
    <div class="{% cycle 'row1' 'row2' %}">
        {% cycle 'row1' 'row2' %}
    </div>
{% endfor %}

P.S。你似乎没有在任何地方使用o,所以我不确定你要做什么。

答案 2 :(得分:12)

现在可能有点太晚了。我制作了这个模板标签来实现这个目标。

from django import template
register = template.Library()

# use @register.assignment_tag
# only when you're working with django version lower than 1.9
@register.simple_tag
def to_list(*args):
    return args

在模板中使用它:

{% load your_template_tag_file %}
{% to_list 1 2 3 4 5 "yes" as my_list %}
{% for i in my_list %}
    {{ i }}
{% endfor %}

此处参考: Django assignment tags

答案 3 :(得分:10)

这里的其他答案看起来像票(至少是我想要的),所以我会提供一个答案,说明为什么你可能想做这样的事情(也许对我的情况有一个更好的答案而不是什么已提供):

我遇到了这个问题,寻找使用Bootstrap构建3个非常相似但不完全相同的按钮的方法。一个按钮可能看起来像

<div class="btn-group">
  <a class="btn btn-primary dropdown-toggle" data-toggle="dropdown" href="#">
    Modality
    <span class="caret"></span>
  </a>
  <ul class="dropdown-menu" id="Modality">
    <li><a href="#">Action</a></li>
  </ul>
</div>

其中按钮之间的区别仅限于按钮的文本(模态,在其上面的行上)和与按钮相关的内容,我们假设它由JS动态填充(引用id =“模态“)。

如果我需要制作其中的10个,复制/粘贴HTML似乎是愚蠢和乏味的,特别是如果我想在事后更改关于我的按钮的任何内容(比如将它们全部拆分下拉)并且它会反对DRY。

所以,相反,在模板中我可以做类似

的事情
{% with 'Modality Otherbutton Thirdbutton' as list %}
  {% for i in list.split %}
    <!-- copy/paste above code with Modality replaced by {{ i }} -->
  {% endfor %}
{% endwith %}

现在,在这种特殊情况下,按钮会为某些相关数据网格添加功能,因此按钮名称也可以从django模型源数据中动态填充,但我不是在我设计的那个阶段现在,你可以看到这种功能在哪里可以维持DRY。

答案 4 :(得分:6)

最简单的是做

{% for x in "123" %}

答案 5 :(得分:2)

drodger是正确的,你不能在故意瘫痪的Django模板语言中做到这一点。当您调用模板尝试模板标记expr时,可以将列表作为上下文变量传入。然后,您可以说{% expr [1,2,3] as my_list %},然后在for循环中使用my_list

答案 6 :(得分:0)

这可能是一个灵感。使用内置过滤器add

{{ first|add:second }}

first is [1, 2, 3] and second is [4, 5, 6], then the output will be [1, 2, 3, 4, 5, 6].

This filter will first try to coerce both values to integers. 
If this fails, it'll attempt to add the values together anyway. 
This will work on some data types (strings, list, etc.) and fail on others. 
If it fails, the result will be an empty string.

官方规范https://docs.djangoproject.com/zh-hans/2.0/ref/templates/builtins/#built-in-filter-reference