Search code examples
stringsplitjinja2

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".


Solution

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