Velocity是一基于java语言的模板引擎, 使用这个简单、功能强大的开发工具,可以很容易的将数据对象灵活的与格式化文档组装到一起。
下面写一个简单的入门例子:
1. 模版文件
- Hello $name! Welcome to $site world!
2. 测试代码
- package com.lht.velocity;
- import java.io.StringWriter;
- import org.apache.velocity.app.VelocityEngine;
- import org.apache.velocity.Template;
- import org.apache.velocity.VelocityContext;
- public class HelloWorld{
- public static void main( String[] args )throws Exception{
- /* first, get and initialize an engine */
- VelocityEngine ve = new VelocityEngine();
- ve.init();
- /* next, get the Template */
- Template t = ve.getTemplate( "hello.vm" );
- /* create a context and add data */
- VelocityContext context = new VelocityContext();
- context.put("name", "VerRan");
- context.put("site", "http://verran.iteye.com");
- /* now render the template into a StringWriter */
- StringWriter writer = new StringWriter();
- t.merge( context, writer );
- /* show the World */
- System.out.println( writer.toString() );
- }
- }
3. 输出结果
- Hello VerRan! Welcome to http://verran.iteye.com world!
注意:
将vm文件放置在项目的根目录下,否则会找不到文件。
续: 循环、判断的使用
- #set( $this = "Velocity")
- $this is great!
- #foreach( $name in $list )
- $name is great!
- #end
- #set( $condition = true)
- #if ($condition)
- The condition is true!
- #else
- The condition is false!
- #end