2010-10-31 34 views
19

我试图使用Jinja2的模板的langauge返回最后n(例如,5)在我的职位列表的帖子:如何访问列表的一部分在Jinja2的

{% for recent in site.posts|reverse|slice(5) %} 
    {% for post in recent %} 
     <li> <a href="/{{ post.url }}">{{ post.title }}</a></li> 
    {% endfor %} 
{% endfor %} 

这是返回整个列表虽然。你如何剥离第一个或最后n个元素?

回答

4

尝试下标符号,就像在普通的Python中一样。例如,把最后的5个员额,并以相反的顺序显示出来:

import jinja2 
tmpl = """\ 
{%- for col in posts[-5:]|reverse|slice(3) -%} 
    {%- for post in col -%} 
     {{ post }} 
    {%- endfor -%} 
    <br> 
{%- endfor -%}""" 
jinja2.Template(tmpl).render(posts=[1,2,3,4,5,6,7]) 

生产:u'76<br>54<br>3<br>'

+0

这很好!谢谢! – 2010-11-04 04:08:45

14

这是我想简单一点,而不使用过滤器:

{% for post in site.posts | reverse | list[0:4] %} 
    <li>&raquo; <a href="/{{ post.url }}">{{ post.title }}</a></li> 
{% endfor %} 

另一种方法是使用loop controls extension

{% for post in site.posts | reverse %} 
    {%- if loop.index > 4 %}{% break %}{% endif %} 
    <li>&raquo; <a href="/{{ post.url }}">{{ post.title }}</a></li> 
{%- endfor %} 
6

我想出了以下代码:

{% for x in xs | batch(n) | first %} 
    ... 
{% endfor %} 

batch(n)滤波器将列表xs入长度n的子列表,则first滤波器选择第一这些子列表的。

+0

我认为这应该是被接受的答案。只要注意,如果想要使用'last'而不是'first',她必须首先通过'list'过滤器传递'batch'的输出。 – Andrew 2017-02-22 18:42:36

10

我也有同样的问题。这是一个简单的答案。这检索site.posts中的最后五项:

{% for recent in site.posts[-5:] %} 
    {% for post in recent %} 
     <li> <a href="/{{ post.url }}">{{ post.title }}</a></li> 
    {% endfor %} 
{% endfor %} 
0

@安德烈的答案有正确的想法。不过,要完全解决你的问题:

{% for recent in site.posts|batch(5)|list|last|reverse %} 
     <li> <a href="/{{ recent.url }}">{{ recent.title }}</a></li> 
{% endfor %} 

或者:

{% for recent in site.posts|reverse|batch(5)|first %} 
     <li> <a href="/{{ recent.url }}">{{ recent.title }}</a></li> 
{% endfor %} 

你使用哪一个取决于你的喜好。

0

对我来说,下面的简单代码工作并不需要整个jinja过滤链。只需使用列表过滤器转换成列表,然后进行正常的阵列切片(注意括号):

{% for recent in (site.posts | list)[-5:] %} 
    {% for post in recent %} 
    <li> <a href="/{{ post.url }}">{{ post.title }}</a></li> 
    {% endfor %} 
{% endfor %} 

我有同样的问题,但我的数据是在一个序列,而不是一个列表,该代码同时处理。