Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape special XML characters in Jinja2 with Ansible

I've got a couple strings I'm trying to substitute into an XML file via Ansible with Jinja. The problem is they have some special characters in them like " and <. To get around this, I'm currently doing this for all the fields in question:

<option name="mystring" value="{{ string_in_ansible | replace("&","&amp;") | replace("'","&apos;") | replace("\"","&quot;") | replace("<","&lt;") | replace(">","&gt;") }}"/>

This is a bit verbose and not at all dry when using with multiple variables. Is there anything built in for this kind of case, or a better way to express this?

like image 317
Chris Avatar asked Feb 01 '26 13:02

Chris


1 Answers

The thing you are looking for is escape, although in your specific circumstance you may actually be happier with xmlattr

like image 121
mdaniel Avatar answered Feb 03 '26 03:02

mdaniel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!