Python Jinja/Flask 中的字符串长度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24163579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 04:07:12  来源:igfitidea点击:

Length of string in Jinja/Flask

pythonflaskjinja2

提问by wuxiekeji

Jinja unfortunately does not support executing arbitrary Python code, such as

不幸的是,Jinja 不支持执行任意 Python 代码,例如

{% if len(some_var)>1 %} ... {% endif %}

My current workaround is to use the deprecated, ugly, double-underscore method:

我目前的解决方法是使用已弃用、丑陋、双下划线的方法:

{% if some_var.__len__()>1 %} ... {% endif %}

Although this works, I'm afraid that some future implementation of strings might break this code. Is there a better way to do this?

虽然这有效,但我担心字符串的某些未来实现可能会破坏此代码。有一个更好的方法吗?

采纳答案by Martijn Pieters

You can use the lengthfilter:

您可以使用length过滤器

{% if some_var|length > 1 %}