Reputation: 514
I'm trying to follow back this example here:
Embed custom filter definition into jinja2 template?
but instead of doing upperstring, I would like to do a boolean flag.
In my jinja2 template, I would like something like this:
{{ set | remediate }} /etc/network/interfaces
I would like it to print 'set' if remediate flag is set to false. When I render, the expected output is:
set /etc/network/interfaces
If the remediate flag is set to true, it will NOT print 'set' when rendered:
/etc/network/interfaces
Using back the example from the link, is there a way I can pass the boolean flag into the function so that when I define it using env.filters['remediate'] = remediate
it will determine whether to output 'set' or not when rendered?
render_config.py
from render import render
def main():
flag = False
render(flag)
render.py
def render(flag):
import jinja2
loader = jinja2.FileSystemLoader('/tmp')
env = jinja2.Environment(autoescape=True, loader=loader)
env.filters['remediate'] = remediate
temp = env.get_template('test.jinja2')
temp.render(set='set')
def remediate(flag):
"""Custom filter"""
return flag
Upvotes: 1
Views: 1733
Reputation: 514
I managed to code a solution that worked for me. I used back the same concept from the example in the link above but modified to evaluate a boolean flag:
def remediate(input):
"""Custom filter"""
if with_remediate == True:
return input
else:
return ''
In my Jinja2 template file, I have something like this..
{{ set | remediate }} /etc/network/interfaces
If a certain function is calling the rendering process of the template, the boolean flag can be set as True or False - depending on what you're trying to achieve. In my particular case, the template above refers to some configs related to a networking device. When showing the configs, the 'set' string is not present. However to configure that line, the 'set' must be included. Two different function, two different purpose, one template used.
In your render() function, you would have something like this:
config = baseline.render(set = 'set ')
This is to allow Jinja2 to know the value 'set' that is passed into remediate is equal to the string 'set '.
Upvotes: 1