9

我们可以使用什么样的条件在 jinja2 中进行分支?我的意思是我们可以使用类似 python 的语句。例如,我想检查标题的长度。如果大于 60 个字符,我想将其限制为 60 个字符并输入“...” 现在,我正在做这样的事情,但它不起作用。error.log 报告 len 函数未定义。

template = Template('''
    <!DOCTYPE html>
            <head>
                    <title>search results</title>
                    <link rel="stylesheet" href="static/results.css">
            </head>
            <body>
                    {% for item in items %}
                            {% if len(item[0]) < 60 %}
                                    <p><a href="{{ item[1] }}">{{item[0]}}</a></p>
                            {% else %}
                                    <p><a href="{{ item[1] }}">{{item[0][40:]}}...</a></p>
                            {% endif %}
                    {% endfor %}
            </body>
    </html>''')

## somewhere later in the code...

template.render(items=links).encode('utf-8')
4

3 回答 3

12

您已经很接近了,您只需将其移至您的 Python 脚本即可。所以你可以像这样定义一个谓词:

def short_caption(someitem):
    return len(someitem) < 60

然后通过将其添加到 'tests' dict 将其注册到环境中):

your_environment.tests["short_caption"] = short_caption

你可以像这样使用它:

{% if item[0] is short_caption %}
{# do something here #}
{% endif %}

欲了解更多信息,这里是关于自定义测试的 jinja 文档

(您只需执行一次,我认为在开始渲染模板之前或之后执行此操作很重要,文档不清楚)

如果你还没有使用环境,你可以像这样实例化它:

import jinja2

environment = jinja2.Environment() # you can define characteristics here, like telling it to load templates, etc
environment.tests["short_caption"] = short_caption

然后通过 get_string() 方法加载您的模板:

template = environment.from_string("""your template text here""")
template.render(items=links).encode('utf-8')

最后,附带说明一下,如果您使用文件加载器,它可以让您进行文件继承、导入宏等。基本上,您只需保存您现在拥有的文件并告诉 jinja 目录在哪里。

于 2012-06-30T05:31:18.700 回答
6

len在jinja2中没有定义,可以使用;

{% if item[0]|length < 60 %}
于 2014-08-11T18:35:40.447 回答
0

Jinja2 现在有一个截断过滤器,可以为你做这个检查

truncate(s, length=255, killwords=False, end='...', leeway=None)

例子:

{{ "foo bar baz qux"|truncate(9) }}
    -> "foo..."

{{ "foo bar baz qux"|truncate(9, True) }}
    -> "foo ba..."

参考:http: //jinja.pocoo.org/docs/2.9/templates/#truncate

于 2017-04-16T07:06:39.377 回答