【问题标题】:if else branching in jinja2如果其他分支在 jinja2
【发布时间】:2023-03-30 16:10:02
【问题描述】:

我们可以使用什么样的条件在 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')

【问题讨论】:

    标签: python wsgi jinja2


    【解决方案1】:

    您已经很接近了,您只需将其移至您的 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 %}
    

    有关更多信息,请参阅custom tests 上的 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 目录在哪里.

    【讨论】:

    • 非常感谢。我会去做。我还发现我也可以通过在查询 db/index 文件本身时检查长度来完成。
    • 很高兴为您提供帮助 :) 您可以单击小复选框接受答案,这样人们就会知道它已经解决了等等
    【解决方案2】:

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

    {% if item[0]|length < 60 %}
    

    【讨论】:

    • 很好 - 这似乎是最 jinjaish(jinjonic?)的方式。
    【解决方案3】:

    Jinja2 现在有一个 truncate 过滤器,它会为你做这个检查

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-03
      相关资源
      最近更新 更多