tweeks200
tweeks200

Reputation: 1947

Jinja2 template variables to one line

Is it possible to create a jinja2 template that puts variables on one line? Something like this but instead of having two lines in the results have them comma separated.

Template:

{% for host in groups['tag_Function_logdb'] %}
elasticsearch_discovery_zen_ping_unicast_hosts = {{ host }}:9300
{% endfor %}

Results:

elasticsearch_discovery_zen_ping_unicast_hosts = 1.1.1.1:9300
elasticsearch_discovery_zen_ping_unicast_hosts = 2.2.2.2:9300

Desired Results:

elasticsearch_discovery_zen_ping_unicast_hosts = 1.1.1.1:9300,2.2.2.2:9300

Edit, this works for 2 items, better solution below:

elasticsearch_discovery_zen_ping_unicast_hosts = {% for host in groups['tag_Function_logdb']  %}
{{ host }}:9300
{%- if loop.first %},{% endif %}
{% endfor %}

Upvotes: 10

Views: 32024

Answers (3)

James Saint-Rossy
James Saint-Rossy

Reputation: 176

Here's the solution that worked for me. I discovered that tweeks200's solution only works for 2 loops. This works regardless of the number of loops. Thanks to everyone here for the help.

elasticsearch_discovery_zen_ping_unicast_hosts={% for host in groups['tag_Function_logdb']  %}
{{ host }}:9300
{%- if not loop.last %},{% endif %}
{% endfor %}

Upvotes: 16

tweeks200
tweeks200

Reputation: 1947

I was able to get this working by putting the directive I wanted before loop and then using the loop.first and - whitespace control to format the comma separated list properly.

elasticsearch_discovery_zen_ping_unicast_hosts = {% for host in groups['tag_Function_logdb']  %}
{{ host }}:9300
{%- if loop.first %},{% endif %}
{% endfor %}

Upvotes: 3

dmitryro
dmitryro

Reputation: 3506

Here's how you can do it:

elasticsearch_discovery_zen_ping_unicast_hosts =  

 {% for host in groups['tag_Function_logdb']  %}

    {{ host }}:9300

    {% if not groups['tag_Function_logdb'].last %}
, 
    {% endif %}

{% endfor %}

Upvotes: 2

Related Questions