# ansible - J2 template

**URL:** <https://forum.ansible.com/t/ansible-j2-template/35446>\
**Category:** Ansible Project\
**Created:** [July 1, 2021, 6:17am UTC](https://forum.ansible.com/t/ansible-j2-template/35446 "2021-07-01T06:17:21Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![dudu.c](https://avatars.discourse-cdn.com/v4/letter/d/278dde/32.png) [@dudu.c](https://forum.ansible.com/u/dudu.c)\
**Post date:** [July 1, 2021, 6:17am UTC](https://forum.ansible.com/t/ansible-j2-template/35446/1 "2021-07-01T06:17:21Z")

</div>

Ansible question  
I have a variable, let call it value1 and a J2 template.

The J2 template includes the following line :  
LINE=” This string mut be included this string is optional= {{ value1}}”

What I need to implement

If value1 is defined with a string – let assume that the string is OK (Value1: OK)  
, the file should be  
LINE=” This string must be included this string is optional= OK”

If value1 is not defined (empty Value1: ) –the file should be  
LINE=” This string must be included”

So how the J2 should be configured?

---

<div class="post-metadata">

**Author:** ![Dick\_Visser](https://avatars.discourse-cdn.com/v4/letter/d/d9b06d/32.png) [@Dick\_Visser](https://forum.ansible.com/u/Dick_Visser)\
**Post date:** [July 1, 2021, 7:25am UTC](https://forum.ansible.com/t/ansible-j2-template/35446/2 "2021-07-01T07:25:30Z")

</div>

LINE=” This string must be included{% if value1 is defined %}  
this string is optional= {{ value1 }}{% endif %}”

---

<div class="post-metadata">

**Author:** ![vbotka](https://sea1.discourse-cdn.com/ansible/user_avatar/forum.ansible.com/vbotka/32/359_2.png) [@vbotka](https://forum.ansible.com/u/vbotka)\
**Post date:** [July 1, 2021, 8:55am UTC](https://forum.ansible.com/t/ansible-j2-template/35446/3 "2021-07-01T08:55:07Z")

</div>

Test the variable is both defined and not empty,  
e.g. (minimal version)

&nbsp;&nbsp;{% if value1 is defined and value1|d('')|length \> 0 %}  
&nbsp;&nbsp;{{ value1 }}  
&nbsp;&nbsp;{% else %}  
&nbsp;&nbsp;This string must be included  
&nbsp;&nbsp;{% endif %}
