使用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/