Updating variable in Ninja for loop

Hello,

I’m trying to create a new string from the keys of a dictionary in a Ninja 2 template. But the variable I’m updating in the for loop seems to reset when the for loop finishes… The following piece of template is just a test to try demonstrate my issue:

`
{% set ssh_allowusers = ‘root’ %}
{% for x in dictusers %}
{{ssh_allowusers }} + {{ x }}
{% set ssh_allowusers = ssh_allowusers ~ ’ ’ ~ x %}
{{ssh_allowusers }}
{% endfor %}
Post Loop: {{ssh_allowusers }}

`

dict_users:

dictusers: willemdh: shell: /bin/zsh groups: wheel shortname: Willem ansi: shell: /bin/sh groups: sysusers,wheel shortname: Willem

But output is:

root + ansi root ansi root ansi + willemdh root ansi willemdh Post Loop: root

Why would the variable reset to ‘root’ after the loop?

Grtz

Willem

I'm trying to create a new string from the keys of a dictionary in a Ninja

You probably mean Jinja and not Ninja :wink:

{% set ssh_allowusers = 'root' %}
{% for x in dictusers %}
{{ssh_allowusers }} + {{ x }}
{% set ssh_allowusers = ssh_allowusers ~ ' ' ~ x %}
{{ssh_allowusers }}
{% endfor %}
Post Loop: {{ssh_allowusers }}

dict_users:

dictusers:
  willemdh:
    shell: /bin/zsh
    groups: wheel
    shortname: Willem
  ansi:
    shell: /bin/sh
    groups: sysusers,wheel
    shortname: Willem

But output is:

root + ansi
root ansi
root ansi + willemdh
root ansi willemdh
Post Loop: root

Why would the variable reset to 'root' after the loop?

A variable set in a block is not available outside the block.
You can read more about it here
http://jinja.pocoo.org/docs/dev/templates/#assignments

Jinja it is :slight_smile:

Solved it with:

AllowUsers {% set ssh_allowusers = ‘root’ %}{% for x in dictusers %}{% set ssh_allowusers = ssh_allowusers ~ ’ ’ ~ x %}{% if loop.last %} {{ssh_allowusers }} {% endif %}{% endfor %}