Python 用 jinja2 替换多个值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36355482/
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 17:46:35  来源:igfitidea点击:

Replace multiple values with jinja2

pythonjinja2

提问by user3605780

I have a variable in jinja2: test1 = "this is value1 and this is value2"

我在 jinja2 中有一个变量: test1 = "this is value1 and this is value2"

with:

和:

{{ test1 | replace("value1","my_value1")  }}

I can replace value1 but I also need to replace value2 how can I do this?

我可以替换 value1 但我也需要替换 value2 我该怎么做?

I tried:

我试过:

{{ test1 | replace("value1","my_value1") | replace("value2","my_value2") }}

But this then only replaces value2.

但这只会替换 value2。

回答by larsks

Your expression seems to work just fine. If I create a template with the jinja2 expression from your question:

你的表情似乎工作得很好。如果我使用您问题中的 jinja2 表达式创建模板:

>>> import jinja2
>>> t = jinja2.Template('{{ test1 | replace("value1","my_value1") | replace("value2","my_value2") }}')

And then render it, passing in a value for test1that contains both of the target replacement strings:

然后渲染它,传入一个test1包含两个目标替换字符串的值:

>>> output = t.render(test1="this has both value1 and value2")

I get a string that has both values replaced:

我得到一个替换了两个值的字符串:

>>> print (output)
this has both my_value1 and my_value2
>>> 

回答by Mohammad Efazati

currently you can replace variable by jinja

目前你可以用jinja替换变量

http://jinja.pocoo.org/docs/2.10/templates/#replace

http://jinja.pocoo.org/docs/2.10/templates/#replace

{{ "Hello World"|replace("Hello", "Goodbye") }}
    -> Goodbye World

{{ "aaaaargh"|replace("a", "d'oh, ", 2) }}
    -> d'oh, d'oh, aaargh