Jinja 中的字符串连接
我只想循环遍历现有列表并从中创建一个逗号分隔的字符串。
像这样的东西: my_string = 'stuff, stuff, stuff, stuff'
我已经知道 loop.last
,我只需要知道如何在我的下面的代码工作。
{% set my_string = '' %}
{% for stuff in stuffs %}
{% set my_string = my_string + stuff + ', '%}
{% endfor%}
I just want to loop through an existing list and make a comma delimited string out of it.
Something like this: my_string = 'stuff, stuff, stuff, stuff'
I already know about loop.last
, I just need to know how to make the third line in my code below WORK.
{% set my_string = '' %}
{% for stuff in stuffs %}
{% set my_string = my_string + stuff + ', '%}
{% endfor%}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
如果
stuffs
是字符串列表,则这样可以:请参阅
加入
过滤器文档,以及一般文档中的过滤器。ps
更读者友好的方式
If
stuffs
is a list of strings, just this would work:See
join
filter documentation, as well as filters in general documentation.p.s.
More reader friendly way
如果您知道所有值都是字符串,则可以使用
+
。 Jinja 还提供了~
运算符,这将确保所有值首先转换为字符串。You can use
+
if you know all the values are strings. Jinja also provides the~
operator, which will ensure all values are converted to string first.不好的是,在试图简化它的过程中,我走得太远了,实际上
stuffs
是各种信息的记录,我只想要其中的 id。我希望
my_sting
成为我的原始代码应该如下所示:
想想看,
stuffs
可能是一本字典,但你明白了要点。是的,我找到了
join
过滤器,并打算像这样处理它:但是如果不导入扩展来执行此操作,附加功能就无法工作,并且阅读该文档让我很头疼。它没有明确说明从哪里导入它,甚至没有明确说明要在哪里放置导入语句,因此我认为找到一种连接方法将是两害相权取其轻。
My bad, in trying to simplify it, I went too far, actually
stuffs
is a record of all kinds of info, I just want the id in it.I want
my_sting
to beMy original code should have looked like this:
Thinking about it,
stuffs
is probably a dictionary, but you get the gist.Yes I found the
join
filter, and was going to approach it like this:But the append doesn't work without importing the extensions to do it, and reading that documentation gave me a headache. It doesn't explicitly say where to import it from or even where you would put the import statement, so I figured finding a way to concat would be the lesser of the two evils.
如果您不能只使用过滤器连接,而是需要对数组的条目执行一些操作:
If you can't just use filter join but need to perform some operations on the array's entry:
另一个黑客可能是这样的。
我有需要连接的字符串数组。所以我将该数组添加到字典中,然后在 for 循环中使用它,效果很好。
Just another hack can be like this.
I have Array of strings which I need to concatenate. So I added that array into dictionary and then used it inside for loop which worked.
您必须使用 join 方法来连接字符串和变量。
下面是如何执行此操作的示例。
You have to use the join method to concatenate strings and variables.
Here is an example of how to do that.
如果列表中的项目是字符串,则通常的 Pythonic 方法可以完美地工作:
The usual pythonic way of doing it works perfectly fine if the items in the list are strings: