Velocity 局部定制模板

Velocity介绍

Velocity是一个基于java的template engine。它允许Web designer引用Java Code中定义的方法。Web designer可以和Java工程师根据MVC模型并发编程。也就是说,Velocity使得Java开发和网页开发分离。

Velocity还可以根据template可以生成web pages, SQL, PostScript和其他输出,或者和其他系统的组件集成。

Velocity Template Language(VTL)

VTL在web site中使用reference嵌入动态内容。变量是reference的一种。比如下面的例子

#set( $a = "Velocity" )

这条VTL语句,#set是指令,$a是变量。String值的变量使用单引号或者双引号括起来,单引号表示raw string,双引号或得到解析后的值。

Rule of thumb: References begin with $ and are used to get something. Directives begin with # and are used to do something.

Reference

VTL有三种reference: 变量, properties和方法。作为使用VTL的设计者,你和你的工程师必须就reference的名字达成一致。这是协议!

  • 变量,以#开头,然后就是identifier。比如 $foo
  • properties,有独特的格式。比如 $customer.name,它可以是map中key=name的值,也可以作为方法调用的缩写
  • 方法,和properties格式相近。比如 $customer.getAddress or $customer.Address

从Velocity 1.6开始,所有array reference被看做是固定长度的list。这意味着你可以在array reference上使用 java.util.List所有方法

Directive

Reference允许template designer在web sites中生成动态内容。指令——使用脚本元素操作Java code的输出

  • #set 用来给变量赋值,只可以是reference类型(变量,properties和methods),literal类型(string, number), arraylist or map
  • #if / #else / #elseif
  • #foreach,遍历
  • #include,原地import本地文件,但是内容不被rendered
  • #parse,不仅可以import VTL文件,还可以parse & render
  • #evaluate,动态evaluate VTL。This allows the template to evaluate a string that is created at render time
  • #block,定义VTL代码块
  • #macro,定义宏
  • ...

Example

最近遇到一个需要局部定制template的case。这要求template能动态render

JavaCode

 

public void test1() {

       VelocityEngine velo = new VelocityEngine();

       velo.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");

       velo.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());

       velo.init();


       VelocityContext context = new VelocityContext();

       Map<String, String> alert = new HashMap<>();

       alert.put("timestamp", "20160719");

       alert.put("policy", "policy description");


       String tpl = "<ul><li>cluster:${alert.timestamp}</li><li>colo:${alert.policy}</li></ul>";

       context.put("tpl" , tpl);

       context.put("alert", alert);


       Template tmpl = velo.getTemplate("ALERT_TEST.vm");

       StringWriter writer = new StringWriter();

       tmpl.merge(context, writer);

       LOG.info(writer.toString());

   }


ALERT_TEST.vm


...

#evaluate($tpl)

Useful Links

  • Velocity中文入门
    • https://github.com/putaoshu/jdf/blob/master/doc/core_vm.md
    • http://www.cnblogs.com/yasin/archive/2010/04/02/1703188.html
  • Velocity官网 
    • http://velocity.apache.org/engine/1.7/user-guide.html#user-guide-contents
  • Bosun Template 
    • https://golang.org/pkg/text/template/
  • Bosun官网 
    • https://bosun.org/quickstart
原文地址:https://www.cnblogs.com/qingwen/p/5692396.html