Skip to content

Instantly share code, notes, and snippets.

@eliasp
Created September 6, 2020 19:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eliasp/abee84d527770fee8940f5b8e291469e to your computer and use it in GitHub Desktop.
Save eliasp/abee84d527770fee8940f5b8e291469e to your computer and use it in GitHub Desktop.
# the expected result would be:
# {'configuration': {'index': 1, 'targets': {'index': 1}}}
# {'configuration': {'index': 2, 'targets': {'index': 2}}}
# the actual result is (see targets.index in 1st line):
# {'configuration': {'index': 1, 'targets': {'index': 2}}}
# {'configuration': {'index': 2, 'targets': {'index': 2}}}
from jinja2 import Environment
from jinja2.ext import do
env = Environment(extensions=[do])
template = env.from_string('''
{%- set template_config = {
'index': none,
'targets': {},
} %}
{%- set projects = {
'foo': {},
'bar': {},
} %}
{%- for project, projectdata in projects.items() %}
{%- set config = template_config.copy() %}
{%- do config.update({"index": loop.index}) %}
{%- do config.targets.update({"index": loop.index}) %}
{%- do projectdata.update({
'configuration': config,
}) %}
{%- endfor %}
{%- for project, projectdata in projects.items() %}
{{ projectdata }}
{%- endfor %}
''')
print(template.render())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment