def main(): args = parser.parse_args() file_path = os.path.abspath(args.file) assert os.path.exists(os.path.abspath(file_path)), "file doesn't exist" tpl = DocxTemplate(file_path) ast = jinja_env.parse(tpl.patch_xml(tpl.get_xml())) variables = meta.find_undeclared_variables(ast) print("Variables: ", variables) context = {} for variable in variables: print("Enter value of variable {}({})".format( variable, variable.replace('_', ''))) line = input("> ") lines = [] while line != 'end': lines.append(line) line = input("> ") line = '\n'.join(lines) context[variable] = Listing(line) print("context: ", context) tpl.render(context) tpl.save("generated.docx")
def is_template(documento): doc = DocxTemplate(MEDIA_ROOT + documento) xml = doc.get_xml() xml = doc.patch_xml(xml) # patch xml for jinja2schema variables = jinja2schema.infer(xml) list_xml = list(variables.keys()) # create a nice list return list_xml
def validate_template_syntax(self, available_placeholders=None, sample_data=None): try: doc = DocxTemplate(self.template) root = _MagicPlaceholder() env = get_jinja_env() ph = { name: root[name] for name in doc.get_undeclared_template_variables(env) } xml = doc.get_xml() xml = doc.patch_xml(xml) image_match = re.match(r".*{{\s?(\S*)\s?\|\s?image\(.*", xml) images = image_match.groups() if image_match else [] for image in images: cleaned_image = image.strip('"').strip("'") ph[root[cleaned_image]] = django_file("black.png").file ph["_tpl"] = doc doc.render(ph, env) if sample_data: sample_data["_tpl"] = doc doc.render(sample_data, env) self.validate_available_placeholders( used_placeholders=root.reports, available_placeholders=available_placeholders, ) except TemplateSyntaxError as exc: arg_str = ";".join(exc.args) raise exceptions.ValidationError( f"Syntax error in template: {arg_str}") finally: self.template.seek(0)