Jinja2用空格分隔字符串 [英] Jinja2 Split string by white spaces

查看:379
本文介绍了Jinja2用空格分隔字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Jinja2模板引擎(+ pelican).

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

我有一个字符串说"a 1",我正在寻找一种将该字符串分成两部分的方法 通过使用空格作为分隔符.

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.

所以我要寻找的最终结果是一个变量,它以数组的形式保存两个值.例如str [0]的计算结果为"a"& str [1]的计算结果为"1".

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

先谢谢了.

推荐答案

我遇到了同样的问题,没有发现任何有用的东西,所以我创建了一个自定义过滤器:

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()

并在模板中使用了它:

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

这篇关于Jinja2用空格分隔字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆