Kajiki XML 引擎库

来源:互联网 发布:淘宝密码忘了无法显示 编辑:程序博客网 时间:2024/05/16 17:23


一、前言

最近接一任务需求,做xml间格式转换的小功能(目标xml提取转为字典-列表数据结构的python脚本也已提供)。觉得通过编码生成xml很繁琐,需要拼接许多xml标签字符串,于是我考虑用xml模板来完成。无意间在Pypi上检索到Kajiki,琢磨几日,果然实现了预期功能。觉得Kajiki模板库比较简单、易于上手,但是相关资料除了官方文档外,少之又少,stackoverflow也少有相关问答,中文相关资料更是没有,于是打算写篇使用心得以抛砖引玉。

<a target=_blankhref="https://pythonhosted.org/Kajiki/index.html"target="_blank">Kajiki项目文档路径</a>

二、xml模板导入方式(python侧)

有两种方式,不过建议通过模板加载器loader加载方式导入模板,这样能做到python与xml模板的解耦。

import kajiki

     loader = kajiki.PackageLoader()

     Template = loader.import_('demo.templates.user_template')

     sample_dict = {'devices': [{'type':'unify', 'name': 'A0'},

                                {'type':'host', 'name': 'H0'},

                                {'type':'controller', 'name': 'C0'}]}

     t = Template(sample_dict).render()

     print t

注意:1).其中demo.templates为python包路径,user_template为xml模板user_template.xml的文件名。

2).sample_dict必须为字典形式,其键将作为全局global变量,甚至嵌套/包含的template仍然可访问使用。

三、xml模板的编辑(xml侧)

1、变量 variable

Template对象创建的入参字典的键即为可访问使用的变量名。在模板标签<py:☒ var>中的变量,可以直接使用;但是其余地方需要加${var}

[1] <span>$devices</span>  

[2] <py:withvars="dev=devices">

    <span>$dev</span>

         </py:with>

2、特殊变量 local

     

[1]<span>$local.__dict__</span> 

   注意:由特殊变量local可获得全局变量字典(local.__dict__['__globals__'])

3、py:with 定义局部变量

有两种写法,

1)第一种嵌入html/xml标签中。定义模板在含模板语法标签内有效。如果存在多个变量以分号间隔。

[1]<spanpy:with="ctr=devices[2]['type']">${ctr}</span>

[2]<spanpy:with="ctr=devices[2]['type'];host=devices[1]['type']">${ctr}and ${host}</span>

2)第二种作为独立模板标签。定义变量在模板标签内有效。

[1] <py:withvars="ctr=devices[2]['type'] ; host=devices[1]['type']">          

        <span>${ctr} and${host}</span>

    </py:with>

     注意:变量中可以像python字典、列表样通过键、索引号获取目标元素。如果有$符号,都需要包含在${}中。

     4、py:for 循环语句

     for循环没有独立的模板标签,只能嵌入html/xml标签中。可设置py:strip在显示时删除所依附的标签。

[1]<spanpy:strip="True" py:for="dev indevices">${dev['type']}</span>   

[2]<spanpy:strip="True" py:for="index inrange(len(devices))">${devices[index]['type']}</span>

[3]<spanpy:strip="True" py:for="type, name in devices.items()">${type} ${name} </span>

注意:for循环里面可以用dict、list方法。</span>

5、py:include 包含子模板template

这样由一个main template,include多个sub template,使得template结构更加简单明了。

[1] <py:includehref="demo.templates.test_temple"/></p>

问题:发现main模板中通过for、with等定义的变量,included子模板中无法访问使用,只能访问全局变量。可通过特殊变量local的全局变量字典作为桥梁,在main模板将变量var设入全局变量字典中,然后在子模块中get该变量。 

点击打开链接

[2]<ppy:strip="True">

<?pylocal.__dict__['__globals__']['dev'] = dev</span>?>

<py:includehref="demo.templates.test_temple"/>

        </p>

6、注释

     <!--! --> 这样的注释将在生成中去掉而不显示。

四、xml模板编辑好后,格式转变就变成字典-列表结构的转变问题啦。

    

 

  


0 0
原创粉丝点击