Method similar to "startswith" in Jinja2 / Flask

I am looking for a method / method similar to running python. What I would like to do is bind some fields in the table that start with "i -".

My steps:

  • I created a filter that returns True / False:

    @app.template_filter('startswith') def starts_with(field): if field.startswith("i-"): return True return False 

then linked it to the template:

 {% 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 %} 

Unfortunately this will not work.

Second step. I did this without a filter, but in a template

 {% 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 %} 

This works, but different data is sent to this template, and it works only for this case. I think that [: 2] may be a bit buggy.

So, I'm trying to write a filter, or maybe there is some method that I skip in the documentation.

+7
flask jinja2
source share
2 answers

Expression {% if {{ field | startswith }} %} {% if {{ field | startswith }} %} will not work because you cannot insert blocks into each other. You will probably succeed with {% if (field|startswith) %} , but a user test , not a filter, would be a better solution.

Something like

 def is_link_field(field): return field.startswith("i-"): environment.tests['link_field'] = is_link_field 

Then in your template you can write {% if field is link_field %}

+2
source share

The best solution....

You can use startswith directly in field.name because field.name returns a string.

 {% if field.name.startswith('i-') %} 

Additionally, you can use any String function, including str.endswith() , for example.

+21
source share

All Articles