user1935336
user1935336

Reputation:

How to include/extend Jinja2 template string variable in another variable

Trying to make the code DRYer by nesting templates like this:

base = Template('''
  - alert:
     cluster: {{cluster}}
     role: {{role}}
     slack: {{slack}}
''')

alert = Template('''
    {% include base %}
     description: Critical {{role}} system load
     threshold: xxx-yyy-zzz
''')

print alert.render(cluster='cluster1', slack='alerts', role='database')

The above does not work, getting the exception:

  File "/usr/local/lib/python2.7/site-packages/jinja2/environment.py", line 989, in render
    return self.environment.handle_exception(exc_info, True)
  File "/usr/local/lib/python2.7/site-packages/jinja2/environment.py", line 754, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "<template>", line 2, in top-level template code
TypeError: no loader for this environment specified

Please advise.

Upvotes: 2

Views: 1770

Answers (1)

hjpotter92
hjpotter92

Reputation: 80657

You are merely not passing the reference to base when rendering alert template.

>>> print alert.render(cluster='cluster1', slack='alerts', role='database', base=base)
################                         just pass this reference of `base` ^

  - alert:
     cluster: cluster1
     role: database
     slack: alerts
     description: Critical database system load
     threshold: xxx-yyy-zzz

Upvotes: 0

Related Questions