Jes*_* 24 python templates jinja2
我正在尝试使用jinja2模板语言返回帖子列表中的最后n个(比方说5个)帖子:
{% for recent in site.posts|reverse|slice(5) %}
{% for post in recent %}
<li> <a href="/{{ post.url }}">{{ post.title }}</a></li>
{% endfor %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
这会返回整个列表.你如何剥离第一个或最后一个元素?
小智 16
在没有使用切片过滤器的情况下,我认为这有点简单:
{% for post in site.posts | reverse | list[0:4] %}
<li>» <a href="/{{ post.url }}">{{ post.title }}</a></li>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
另一种方法是使用循环控件扩展:
{% for post in site.posts | reverse %}
{%- if loop.index > 4 %}{% break %}{% endif %}
<li>» <a href="/{{ post.url }}">{{ post.title }}</a></li>
{%- endfor %}
Run Code Online (Sandbox Code Playgroud)
joe*_*phy 13
我也有同样的问题.这是一个简单的答案.这将检索site.posts中的最后五个项目:
{% for recent in site.posts[-5:] %}
{% for post in recent %}
<li> <a href="/{{ post.url }}">{{ post.title }}</a></li>
{% endfor %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
And*_*ikh 10
我想出了以下代码:
{% for x in xs | batch(n) | first %}
...
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
该batch(n)滤波器将列表xs入长度的子列表n,则该first过滤器选择第一这些子列表的.
尝试下标表示法,就像在普通 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])
Run Code Online (Sandbox Code Playgroud)
产生: u'76<br>54<br>3<br>'
对我来说,以下简单的代码可以工作,并且不需要整个 jinja 过滤器链。只需使用列表过滤器转换为列表,然后进行正常的数组切片(注意括号):
{% for recent in (site.posts | list)[-5:] %}
{% for post in recent %}
<li> <a href="/{{ post.url }}">{{ post.title }}</a></li>
{% endfor %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
我遇到了同样的问题,但我的数据是序列而不是列表,并且此代码可以处理这两个问题。