Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating punctuation free lists?

Tags:

python

jinja2

Normally you define list in jinja like this :

{% set lst = ['abc','def','egh', .... ] %}

Is there a way to write plain text inside the template and then parse it somehow into list. f.e.:

{% set lst <= abc def egh ....%}

also allow it to be multi-line.

the reason is that i need to write many big lists inside the templates

like image 477
sten Avatar asked Feb 05 '26 10:02

sten


1 Answers

For instance, you can use split method of the strings directly from the jinja2 template. Like this:

{% set text %}abc def jhi{% endset %}
{% set strings=text.split(' ') %}
>> {{ strings }} <<

will give you:

>> ['abc', 'def', 'jhi'] <<

In this sample strings variable contains array of strings splitted by the space. In this sample original string splitted by the new line:

{% set text -%}
abc
def
jhi
{%- endset %}
{% set strings=text.split('\n') %}
>> {{ strings }} <<

With the same result. You can use other string functions like partition, rsplit etc. as well.

like image 113
Sergei Sadovnikov Avatar answered Feb 08 '26 00:02

Sergei Sadovnikov