使用jinja2自动生成代码

使用jinja2自动生成代码

编辑器经常需要添加新的变量来给策划配置,程序写好代码后往往会对编辑器进行修改,或者配置进行修改,可以使用jinja2自动生成代码和配置文件来减少工作量。

安装jinja2

如果使用pycharm, 直接File-Settings-Project:xxx-Project Interpreter
在这里插入图片描述
安装Jinja2即可。

简单的例子

import sys
reload(sys)
sys.setdefaultencoding('utf-8')
from jinja2 import Template

template_filename = 'test.tpl'

def mytest():
	try:
		with open(template_filename, 'r') as f:
			node_doc_template = Template(f.read().decode('utf-8'))
			f.close()
	except Exception as e:
		print '[ERROR] Parse tpl file fal: %s' % e
		return

	module_list={}
	res = node_doc_template.render(
		DATA=module_list,
		seq=[{'type':'str', 'subtype':'1111111' },{'type':'list', 'subtype':'str' }]
	)

	with open('test.txt', 'w+') as f:
		f.write(res.encode('utf-8'))
		f.close()

	return res

if __name__ == '__main__':
    mytest()

模板test.tpl内容:

# -*- encoding: utf-8 -*-

#本代码自动生成,请勿手动修改
{% macro test_fuc(item) %}
    {%- if item.type == 'str' -%}
    str 'check_time': {{item}}
    {%- elif item.type == 'list' -%}
    list 'check_time': {{item}},child={{test_fuc(item.subtype)}}
    {%- else -%}
    other 'check_time': {{item}}, what the fuck else
    {%- endif -%}
{% endmacro %}
<div>
    {%- for item in seq %}
        {{test_fuc(item)}}
    {%- endfor %}
</div>

生成的内容:

# -*- encoding: utf-8 -*-

#本代码自动生成,请勿手动修改

<div>
        str 'check_time': {'subtype': '1111111', 'type': 'str'}
        list 'check_time': {'subtype': 'str', 'type': 'list'},child=other 'check_time': str, what the fuck else
</div>

参考文档

  • https://jinja.palletsprojects.com/en/master/templates/
  • http://docs.jinkan.org/docs/jinja2/
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值