Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace multiple values with jinja2

Tags:

python

jinja2

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.

like image 517
user3605780 Avatar asked Apr 01 '16 11:04

user3605780


People also ask

Are Jinja2 functions markupsafe?

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 ¶

How to replace an undefined variable with a string in Jinja?

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.

How to check if a variable exists in Jinja2?

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.

How do I use conditionals in Jinja2?

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.


1 Answers

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
>>> 
like image 107
larsks Avatar answered Oct 17 '22 06:10

larsks