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:
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.
there are two delimiters to split by here: first it's ",", and then the elements themselves are split by ":".
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.
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.
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 %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With