创建一个模板解析的功能函数

第一步:生成目录结构

config_file
|_templates
| |_nginx.conf.j2
|_nginx.conf

第二步:写一个用于解析模板的函数

from jinja2 import PackageLoader,Environment

def j2(package_name,package_path,template_name,file_name,*args,**kwargs):
    env = Environment(loader=PackageLoader(package_name,package_path))
    template = env.get_template(template_name) 
    t=template.render(*args,**kwargs)
    with open(file_name,'w') as f:
        f.write(t)

第三步:执行函数

j2('config_file','templates','nginx.conf.j2','nginx.conf',name='123')

执行完毕会生成解析过的nginx.conf 配置文件。

上面的工具使用了一段时间发下传入变量多的事后很不方便,于是修改变量从yaml 文件中传入。代码如下

from jinja2 import PackageLoader,Environment
import yaml

def j2(package_name,package_path,template_name,file_name,vars_file):
    env = Environment(loader=PackageLoader(package_name,package_path))
    template = env.get_template(template_name)

    try:
        with open(vars_file) as f:
            vars=yaml.safe_load(f)

        t=template.render(vars)
        with open(file_name,'w') as f:
            f.write(t)
    except:
        exit
posted @ 2023-01-28 17:56  mingtian是吧  阅读(22)  评论(0编辑  收藏  举报