Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method similar to 'startswith' in Jinja2/Flask

Tags:

flask

jinja2

I'm looking for method/way which is similar to python's startswith. What I would like to do is link some fields in table which start with "i-".

My steps:

  1. I have created filter, which return True/False:

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

then linked it to 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 %}

Unfortunatetly, it doesn't work.

Second step. I did it without filter, but in 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 %}

That works, but to that template are sending different datas, and it works only for this case. I'm thinking that [:2] could be buggy a little bit.

So I try to write filter or maybe there is some method which I skip in documentation.

like image 631
Ojmeny Avatar asked Feb 05 '15 14:02

Ojmeny


People also ask

How many delimiters are there in Jinja2?

there are two delimiters to split by here: first it's ",", and then the elements themselves are split by ":".

How do you write a for loop in Jinja2?

Jinja2 being a templating language has no need for wide choice of loop types so we only get for loop. For loops start with {% for my_item in my_collection %} and end with {% endfor %} . This is very similar to how you'd loop over an iterable in Python.


2 Answers

A better solution....

You can use startswith directly in field because field is a python String.

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

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

like image 92
Frederico Oliveira Avatar answered Oct 05 '22 14:10

Frederico Oliveira


The expression {% if {{ field | startswith }} %} will not work because you cannot nest blocks inside each other. You can probably get away with {% if (field|startswith) %} but a custom test rather than 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 %}

like image 36
kylewm Avatar answered Oct 05 '22 15:10

kylewm