CommonTemplate增加HTML标签版语法外套
CommonTemplate(http://www.commontemplate.org)已提供了注释版和属性版语法外套.注释版语法外套:
<html> <body> <!--$if{users != null && users.size &amp;gt; 0}--> <table border="1"> <!--$for{user : users}--> <tr> <td><!--$output{for.index + 1}-->1<!--$end--></td> <td><!--$output{user.name}-->james<!--$end--></td> <td><!--$output{user.coins}-->2.00<!--$end--></td> </tr> <!--$end--> </table> <!--$end--> </body></html>
属性版语法外套:
<html> <body> <table ct:if="users != null && users.size &amp;gt; 0" border="1"> <tr ct:for="user : users"> <td><span ct:output="for.index + 1">1</span></td> <td><span ct:output="user.name">james</span></td> <td><span ct:output="user.coins">2.00</span></td> </tr> </table> </body></html>
当模板应用于XML/HTML时, 可能需要保持完整的DOM模型结构,
属性版语法外套也可以做到, 但转换比较耗时, 且存在不规则HTML语法兼容问题.
桂林提议加入XML/HTML标签版语法外套, 使用如:
<html> <body> <ct:if param="users != null && users.size &amp;gt; 0"> <table border="1"> <ct:for param="user : users"> <tr> <td><ct:out param="for.index + 1"/></td> <td><ct:out param="user.name"/></td> <td><ct:out param="user.coins"/></td> </tr> </ct:for> </table> </ct:if> </body></html>
其结构与标准语法是一对一的, 转换起来非常方便.
使用ResourceFilter扩展点进行实现,
在资源加载时使用简单的正则表达式替换,
不解析HTML语法,也就没有不规则HTML语法兼容问题,
只用了两条正则表达式, 就完成了转换:
text = text.replaceAll("\\<ct\\s*\\:\\s*(+)\\s+param\\s*\\=\\s*\\"([^\\"]+)\\"\\s*\\/?\\>", "\\$$1{$2}");text = text.replaceAll("\\<\\/\\s*ct\\s*\\:\\s*(+)\\s*\\>", "\\$end{$1}");
加载模板资源时有内存消耗和转换时间消耗,但消耗不是很大,
从0.8.7版本开始支持.
参见:
http://www.commontemplate.org
页:
[1]