助力软件开发企业降本增效 PHP / java源码系统,只需一次付费,代码终身使用! 广告
默认下,下面的函数在全局作用域中可用: range([*start*], *stop*[, *step*])[](http://docs.jinkan.org/docs/jinja2/templates.html#range "Permalink to this definition") 返回一个包含整等差级数的列表。 range(i, j) 返回 [i, i+1, i+2, ...., j-1] ;起始值(!)默认为 0 。当给定了公差,它决定了增长(或减小)。 例如 range(4) 返回 [0, 1, 2, 3] 。末端的值被丢弃了。这些是一个 4 元素 数组的有效索引值。 例如重复一个模板块多次来填充一个列表是有用的。想向你有一个 7 个用户的 列表,但你想要渲染三个空项目来用 CSS 强制指定高度: ~~~ <ul> {% for user in users %} <li>{{ user.username }}</li> {% endfor %} {% for number in range(10 - users|count) %} <li class="empty"><span>...</span></li> {% endfor %} </ul> ~~~ lipsum(*n=5*, *html=True*, *min=20*, *max=100*)[](http://docs.jinkan.org/docs/jinja2/templates.html#lipsum "Permalink to this definition") 在模板中生成 lorem ipsum 乱数假文。默认会生成 5 段 HTML ,每段在 20 到 100 词之间。如果 HTML 被禁用,会返回常规文本。这在测试布局时生成简单内容时很有 用。 dict(***items*)[](http://docs.jinkan.org/docs/jinja2/templates.html#dict "Permalink to this definition") 方便的字典字面量替代品。 {'foo' : 'bar'} 与 dict(foo=bar) 等价。 *class *cycler(**items*)[](http://docs.jinkan.org/docs/jinja2/templates.html#cycler "Permalink to this definition") 周期计允许你在若干个值中循环,类似 loop.cycle 的工作方式。不同于 loop.cycle 的是,无论如何你都可以在循环外或在多重循环中使用它。 比如如果你想要显示一个文件夹和文件列表,且文件夹在上,它们在同一个列表中且 行颜色是交替的。 下面的例子展示了如何使用周期计: ~~~ {% set row_class = cycler('odd', 'even') %} <ul class="browser"> {% for folder in folders %} <li class="folder {{ row_class.next() }}">{{ folder|e }}</li> {% endfor %} {% for filename in files %} <li class="file {{ row_class.next() }}">{{ filename|e }}</li> {% endfor %} </ul> 周期计有下面的属性和方法: ~~~ reset()[](http://docs.jinkan.org/docs/jinja2/templates.html#cycler.reset "Permalink to this definition") 重置周期计到第一个项。 next()[](http://docs.jinkan.org/docs/jinja2/templates.html#cycler.next "Permalink to this definition") 返回当前项并跳转到下一个。 current[](http://docs.jinkan.org/docs/jinja2/templates.html#cycler.current "Permalink to this definition") 返回当前项。. New in version 2.1. *class *joiner(*sep='*, *'*)[](http://docs.jinkan.org/docs/jinja2/templates.html#joiner "Permalink to this definition") 一个小巧的辅助函数用于“连接”多个节。连接器接受一个字符串,每次被调用时返回 那个字符串,除了第一次调用时返回一个空字符串。你可以使用它来连接: ~~~ {% set pipe = joiner("|") %} {% if categories %} {{ pipe() }} Categories: {{ categories|join(", ") }} {% endif %} {% if author %} {{ pipe() }} Author: {{ author() }} {% endif %} {% if can_edit %} {{ pipe() }} <a href="?action=edit">Edit</a> {% endif %} ~~~ New in version 2.1.