I have a variable in 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?
I tried:
{{ test1 | replace("value1","my_value1") | replace("value2","my_value2") }}
But this then only replaces value2.
Jinja2 functions (macros, super, self.BLOCKNAME) always return template data that is marked as safe. String literals in templates with automatic escaping are considered unsafe because native Python strings (str, unicode, basestring) are not markupsafe.Markup strings with an __html__ attribute. List of Control Structures ¶
By default, when encountering an evaluation statement with undefined variable Jinja will replace it with an empty string. This often comes as a surprise to people writing their first templates. This behavior can be changed by setting argument undefined, taken by Template and Environment objects, to a different Jinja undefined type.
If you simply want to check if the variable exists then is defined test, which we'll look at shortly, is usually a better choice. Tests in Jinja2 are used with variables and return True or False, depending on whether the value passes the test or not. To use this feature add is and test name after the variable.
Conditionals in Jinja2 can be used in a few different ways. We'll now have a look at some use cases and how they combine with other language features. First thing we look at is comparing values with conditionals, these make use of ==, !=, >, >=, <, <= operators. These are pretty standard but I will show some examples nonetheless.
Your expression seems to work just fine. If I create a template with the jinja2 expression from your question:
>>> import jinja2
>>> t = jinja2.Template('{{ test1 | replace("value1","my_value1") | replace("value2","my_value2") }}')
And then render it, passing in a value for test1
that contains both
of the target replacement strings:
>>> 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
>>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With