10

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 %}
tweeks200
  • 1,837
  • 5
  • 21
  • 33
  • 1
    Possible duplicate of [How to output a comma delimited list in jinja python template?](http://stackoverflow.com/questions/11974318/how-to-output-a-comma-delimited-list-in-jinja-python-template) – nelsonda May 18 '17 at 13:26
  • "this works" is not correct (or, only correct for two items) - please re-edit "this works for two items" – Gedge Oct 08 '19 at 12:41
  • @gedge done, thanks for pointing that out – tweeks200 Oct 08 '19 at 15:16

3 Answers3

15

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 %}
Garrett Hyde
  • 5,409
  • 8
  • 49
  • 55
3

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 %}
tweeks200
  • 1,837
  • 5
  • 21
  • 33
2

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 %}
dmitryro
  • 3,463
  • 2
  • 20
  • 28
  • Thanks, making some progress. The `elasticsearch_discovery_zen_ping_unicast_hosts =  ` is not being populated and instead just showing as text. Should that be in part of the loop somehow? – tweeks200 Jun 28 '16 at 13:53