在Jinja2/Flask中类似于'startswith'的方法

Ojm*_*eny 10 jinja2 flask

我正在寻找类似于python的开头的方法/方式.我想要做的是链接表格中以"i-"开头的一些字段.

我的步骤:

  1. 我创建了filter,返回True/False:

    @app.template_filter('startswith')
    def starts_with(field):
        if field.startswith("i-"):
                return True
        return False
    
    Run Code Online (Sandbox Code Playgroud)

然后将其链接到模板:

{% for field in row %}
            {% if {{ field | startswith }} %}
               <td><a href="{{ url_for('munin') }}">{{ field | table_field | safe }}</a></td>
            {% else %}
               <td>{{ field | table_field | safe}}</td>
            {% endif %}
     {% endfor %}
Run Code Online (Sandbox Code Playgroud)

不幸的是,它不起作用.

第二步.我没有使用过滤器,但在模板中

{% for field in row %}
            {% if field[:2] == 'i-' %}
               <td><a href="{{ url_for('munin') }}">{{ field | table_field | safe }}</a></td>
            {% else %}
               <td>{{ field | table_field | safe}}</td>
            {% endif %}
     {% endfor %}
Run Code Online (Sandbox Code Playgroud)

这是有效的,但是该模板正在发送不同的数据,它只适用于这种情况.我认为[:2]可能会有点儿错误.

所以我尝试编写过滤器,或者有一些方法可以在文档中跳过.

Fre*_*ira 47

更好的解决方案....

您可以直接在field.name中使用startswith,因为field.name返回一个String.

{% if field.startswith('i-') %}
Run Code Online (Sandbox Code Playgroud)

此外,您可以使用任何String函数,str.endswith()例如,包括.


kyl*_*ewm 4

该表达式{% if {{ field | startswith }} %}将不起作用,因为您不能将块嵌套在彼此内部。您可能可以摆脱困境,{% if (field|startswith) %}自定义测试而不是过滤器将是更好的解决方案。

就像是

def is_link_field(field):
    return field.startswith("i-"):

environment.tests['link_field'] = is_link_field
Run Code Online (Sandbox Code Playgroud)

然后在你的模板中,你可以写{% if field is link_field %}

  • 大家请看下面的答案 (2认同)