Odoo-Tutorial/cenhomes_student/models/template.py
2025-03-04 16:53:07 +07:00

37 lines
1.6 KiB
Python

class SimpleTemplate:
def __init__(self, template: str):
self.template: str = template
def render(self, context):
# Loop through context items
ret = self.template
for key, value in context.items():
if key.startswith("loop:"):
# If the key starts with "loop:", handle loop processing
loop_name = key[len("loop:"):]
start = f"{{{{loop:variable.{loop_name} as item}}}}"
end = f"{{{{end_loop:variable.{loop_name}}}}}"
if start not in ret:
continue
idx_start = ret.index(start) + len(start)
idx_end = ret.index(end)
template_child = ret[idx_start:idx_end]
ret = ret[:(idx_start - len(start))] + ret[idx_end:]
loop_content = ""
for item in value:
loop_content += self.render_columns(template_child, item)
ret = ret.replace(end, loop_content)
else:
# If not a loop, replace the placeholder with the value
value = str(value).replace('\n', '<br>') if value not in [False, None] else ''
ret = ret.replace(f"{{{{variable.{key}}}}}", str(value))
return ret
def render_columns(self, child_template: str, item: dict):
for k, v in item.items():
child_template = child_template.replace(
f"{{{{item.{k}}}}}",
str(v).replace('\n', '<br>') if v not in [False, None] else ''
)
return child_template