Jinja append in same line after if-else

Viewed 191

I have the following piece of HTML:

<li style="margin-bottom: 3px; margin-top: 3px">Vendor accounts:</li>
{% if fact_foundVendorList is defined and fact_foundVendorList|length > 0 %}
   {% for vendor in fact_foundVendorList %}
      <ul>
         <li style="margin-bottom: 3px; margin-top: 3px">{{ vendor }}</li>
      </ul>
   {% endfor %}
{%- else -%}
No accounts were found for the user
{%- endif -%}

When the if fact_foundVendorList returns to be false, it will look like this:

* Vendor accounts:
    No vendor accounts were found for the user 

Otherwise, it would like something like:

 * Vendor accounts:
    * account1
    * account2

I only want to change the false output. In case it's false I want to have the message in the same line as the "vendor accounts" line. So it should look like this:

* Vendor accounts: No accounts were found for the user.

I thought adding the following %- -% would work, but I think I need something else

{%- else -%}
No accounts were found for the user
{%- endif -%}

I saw various related solutions online but couldn't apply it to my case without breaking the structure of the <ul> and <li> tags in my template. It's a long document.

1 Answers

Your issue here lies on the fact that you will have to have the No accounts were found for the user inside the <li> containing Vendor accounts:, otherwise it won't be on the same line, as you want your list to be of the default display: list-item type.

What you can do, then, is to create a variable with the condition, then use it to display the message.

{% set has_account = fact_foundVendorList | default([]) | length > 0 %}

<li style="margin-bottom: 3px; margin-top: 3px">
  Vendor accounts: {% if not has_account %}No accounts were found for the user{% endif %}
</li>
{% for vendor in fact_foundVendorList | default([]) %}
  <ul>
    <li style="margin-bottom: 3px; margin-top: 3px">{{ vendor }}</li>
  </ul>
{% endfor %}

Note that: by defining a default value to an empty list, you do not need to assert if the list is defined for the length filter to be able to give you the correct information

Related