Building an object in variables depending on if a field exists or not

Hello. I have a script that has three fields: title, message, image. They are all of type text. The first two are required and the image one is optional. I’m trying to build a variable that looks like this:

 data:
   title: "{{ title }}"
   message: "{{ message }}"
   data:
     image: "{{ image }}"

but I only want the data and image to show up if image was provided. Can someone help me with the syntax for this?

For example, if I provide all three, it would show up like

 data:
   title: "title"
   message: "message"
   data:
     image: "/some_url.png"

but if I only had title and message, it would only show up like:

 data:
   title: "title"
   message: "message"

Please format configuration blocks properly, including indentation. Without proper indentation, there is no way for us to know the actual structure you are trying to achieve.

I fixed the formatting. Though the question didn’t really need it to, so I put a bit more in the question if it wasn’t clear.

This should work:

data: >
  {% set a =  {"title": title, "message": message} %}
  {% if image is defined %}
    {{ dict(a, **{"data":{"image":image}}) }}
  {% else %}
    {{ a }}
  {% endif %}

1 Like