Add for_each and template_if_empty

This commit is contained in:
PapaTutuWawa 2022-05-12 15:42:37 +02:00
parent a1eb445bff
commit 00e3ef6987

View File

@ -124,8 +124,40 @@ def read_content(filename):
def render(template, **params): def render(template, **params):
"""Replace placeholders in template with values from params.""" """Replace placeholders in template with values from params."""
return re.sub(r'{{\s*([^}\s]+)\s*}}', def handle_variable(match):
lambda match: str(params.get(match.group(1), match.group(0))), var = match.group(1).strip()
if match.group(1).startswith("template "):
import_name = var[7:]
import_ = fread(import_name)
return render(import_, **params)
elif var.startswith("for_each "):
args = var.split(" ")[1:]
attribute_name = args[0]
template_name = args[1]
template_ = fread(template_name)
templates = []
for val in params.get(attribute_name, []):
templates.append(render(template_, **params, item=val))
return "\n".join(templates)
elif var.startswith("item."):
return str(params["item"].get(var[5:], match.group(0)))
elif var.startswith("template_if_empty "):
# {{ template_if_empty <param> <template if param is empty> <otherwise> }}
args = var[17:].split(" ")[1:]
value = params["item"].get(args[0][5:], "") if args[0].startswith("item.") else params.get(args[0], "")
template_name = args[1] if value == "" else args[2]
template_ = fread(template_name)
return render(template_, **params)
else:
if not var in params:
print("Did not find variable '%s'!" % var)
return match.group(0)
return params[var]
return re.sub(r'{{\s*([^}]+)\s*}}',
handle_variable,
template) template)
@ -238,7 +270,7 @@ def main():
if os.path.isfile(params_file): if os.path.isfile(params_file):
params.update(**json.loads(fread(params_file))) params.update(**json.loads(fread(params_file)))
for variable in options.variables: for variable in (options.variables or []):
key, val = variable.split('=') key, val = variable.split('=')
params[key] = val params[key] = val