Using custom filters with Jinja
The exists_with_value
filer returns true if the token provided exists and is not empty.
def exists_with_value(token):
return token is not None and len(token) > 0
The last line below adds the function to Jinja
def load_template(template_file):
full_template_path = os.path.join(DATA_PATH, TEMPLATES_PATH, template_file)
if not os.path.exists(full_template_path):
print_error(f'Template file not found: {template_file}')
sys.exit(1)
template_filename = os.path.basename(full_template_path)
template_path = os.path.dirname(full_template_path)
template_loader = jinja2.FileSystemLoader(searchpath=template_path, encoding=ENCODING)
template_env = jinja2.Environment(loader=template_loader, lstrip_blocks=True, trim_blocks=True)
template_env.filters['exists_with_value'] = exists_with_value
Use it like this: