{% if %} under data?

Hello,

I have this in a script:

action: notify.mobile
data:
  title: "{{ title }}"
  message: "{{ message }}"
  data:
    tag: "{{ tag }}"
    car_ui: "{{ car_ui }}"
    notification_icon: "{{ icon }}"
    actions:
      - action: "{{ action }}"
        title: "{{ action_title }}"
        uri: "{{ action_uri }}"

If I don’t have the action variables defined then I get a warning in the logs.

I was thinking of doing something like this:

action: notify.mobile
data:
  title: "{{ title }}"
  message: "{{ message }}"
  data:
    tag: "{{ tag }}"
    car_ui: "{{ car_ui }}"
    notification_icon: "{{ icon }}"
    {% if action defined %}
    actions:
      - action: "{{ action }}"
        title: "{{ action_title }}"
        uri: "{{ action_uri }}"
    {% endif %}

but then find out that doesn’t work.

Error:
Message malformed: template value should be a string dictionary value @ data[‘sequence’][0][‘data’]

I was thinking I’d use an if-then block for checking {{ action is defined }}, but I was hoping there might be a cleaner way of doing it. Then, if I need to modify the notify action then I’d only have to change it once.

I hope that all makes sense.

Thanks!

Did a quick test, and the action accepts an empty list for actions
So you can do

action: notify.mobile
data:
  title: "{{ title }}"
  message: "{{ message }}"
  data:
    tag: "{{ tag }}"
    car_ui: "{{ car_ui }}"
    notification_icon: "{{ icon }}"
    actions: >
      {% if action is defined %}
        {{ [dict(action=action, title=action_title, uri=action_uri)] }}
      {% else %}
        {{ [] }}
      {% endif %}
3 Likes

You can also template the entire data section. In this case the suggestion from TheFes is the better/easier approach. But for scenarios where you can’t supply an empty list (which are more common), you can template the entire data section and simply omit the key that you don’t want.

action: notify.mobile
data:
  title: "{{ title }}"
  message: "{{ message }}"
  data: >
    {% set ns = namespace(data_dict = dict(
      tag=tag, car_ui=car_ui, notification_icon=icon)) %}
    {% if action is defined %}
      {% set actions_dict = [dict(action=action, title=action_title, uri=action_uri)] %}
      {% set ns.data_dict = dict(actions=actions_dict, **ns.data_dict) %}
    {% endif %}
    {{ ns.data_dict }}
1 Like