elad.chen
elad.chen

Reputation: 2425

Jinja2 Split string by white spaces

I'm using Jinja2 template engine (+pelican).

I have a string saying "a 1", and I am looking for a way to split that string in two by using the white-space as the delimiter.

So the end result I'm looking for is a variable which holds the two values in a form of an array. e.g. str[0] evaluates to "a" & str[1] evaluates to "1".

Upvotes: 21

Views: 52208

Answers (6)

User2403
User2403

Reputation: 185

I'd suggest to use something like:

str = "a 1 b 2 c 3"
val = atr.split()

Also, if you want to point a specific position then you can use something like:

val1 = atr.split()[2]

This will put second value in val1.

Upvotes: 3

Jeremy Jones
Jeremy Jones

Reputation: 5641

You can also do this with a decorator:

from flask import Flask
app = Flask(__name__)

@app.template_filter('split_space')
def split_space_filter(s):
    return s.strip().split()

if __name__ == '__main__':
    app.run()

Upvotes: 0

Tim Raasveld
Tim Raasveld

Reputation: 111

I made a little plugin that does the same as Loïc's answer but it optionally specifying a separator. https://github.com/timraasveld/ansible-string-split-filter

It allows you to type:

# my_variable = 'a 1`
{ my_variable | split | join(' and ') } #=> a and 1

Upvotes: 3

dragon
dragon

Reputation: 105

my solution is tested in iPython

In [1]: from jinja2 import Template
In [2]: Template("{{s.split('-')}}").render(s='a-bad-string')
Out[2]: u"['a', 'bad', 'string']"

Upvotes: 4

Loïc
Loïc

Reputation: 11942

I had the same issue and didn't find anything useful, so I just created a custom filter :

def split_space(string):
    return string.strip().split()

Added it to the filter list (with flask):

app = Flask(__name__)

def split_space(string):
    return string.strip().split()

#some code here

if __name__ == '__main__':

    app.jinja_env.filters['split_space'] = split_space
    app.run()

And used it as such in the template :

{% if "string" in element|split_space %} ... {% endif %}

Upvotes: 17

Jakub Kotowski
Jakub Kotowski

Reputation: 7571

Calling split on the string should do the trick:

"a 1".split()

Upvotes: 29

Related Questions