2017-07-26 52 views
1

如果我的对象是 {(title: 'one', content: 'foo'), (title: 'two', content: 'bar')} 我该如何去获得'为'和'栏'到我的模板?我有一个对象列表,并希望返回一个属性与另一个属性

事情是这样的:

{% for content in content_list where content.title='one'} 
{{ content.content }} 

在 '富' 由此而来。

{% for content in content_list where content.title='two'} 
{{ content.content }} 

产生'酒吧'。

+0

你为什么不使用,如果?? – Exprator

+0

在模板上下文中添加两个列表会更快,更易于阅读。 –

回答

2

试试这个 -

{% for content in content_list %} 
    {% if content.title == 'two' %} 
     {{ content.content }} 
    {% else %} 
     {{ content.content }} 
    {% endif %} 
{% endfor %} 

注意:只有在列表很小

+0

嗯,这给出了: TemplateSyntaxError at/ 行114上的块标记无效:'endfor',预计'endblock'。你忘了注册或加载这个标签吗? 这对我没有任何意义 – Chris

+0

我在%循环结束时错过了%}:编辑的代码 – Vaibhav

0

如果你想分割你的内容在列中,只需为每种对象创建一个列表并遍历它们。

在你看来,做这样的事情:

l1 = [(title: 'one', content: 'foo'),] # All the objects with title 'one' 
l2 = [(title: 'two', content: 'bar'),] # All the objects with title 'two' 
context = {'content_list1': l1, 'content_list2': l2} 

而在你的HTML迭代在每个名单:

{% for content in content_list1 %} 
{{ content.content }} 
{% endfor %} 

{% for content in content_list2 %} 
{{ content.content }} 
{% endfor %} 

我希望这是你在找什么。

相关问题