def render_template(template_file, target_file, config, verbose=False): filename, file_extension = os.path.splitext(template_file) basename = os.path.basename(template_file) if ("render-exclude" in config and basename in config["render-exclude"]): # Don't render/copy the file. return if ("render-by-copy-ext" in config and file_extension in config["render-by-copy-ext"]) or ( "render-by-copy" in config and basename in config["render-by-copy"]): copyfile(template_file, target_file) if verbose: print("Copy tempalte " + template_file + " --> " + target_file) elif "render-by-copy-full" in config and template_file in config[ "render-by-copy-full"]: copyfile(template_file, target_file) if verbose: print("Copy tempalte " + template_file + " --> " + target_file) elif ("render-by-line-ext" in config and file_extension in config["render-by-line-ext"]) or ( "render-by-line" in config and basename in config["render-by-line"]): if verbose: print("Render template " + template_file + " --> " + target_file + " Line by Line .... ") ENV_local = Environment(loader=FileSystemLoader("/")) with open(target_file, 'w') as f: with open(template_file, 'r') as fr: for line in fr: print("Read: " + line) try: template = ENV_local.Template(line) content = template.render(cnf=config) print(content) f.write(content + "\n") except: pass fr.close() f.close() else: if verbose: print("Render template " + template_file + " --> " + target_file) try: ENV_local = Environment(loader=FileSystemLoader("/")) template = ENV_local.get_template(os.path.abspath(template_file)) content = template.render(cnf=config) target_dir = os.path.dirname(target_file) if target_dir != '': os.system("mkdir -p {0}".format(target_dir)) with open(target_file, 'w') as f: f.write(content) f.close() except Exception as e: print("!!! Failure !!! in render template " + template_file) print(e) pass