FreeMarker第一例

本文通过实现一个简单的FreeMarker模板示例来解释如何将Java数据传递到模板中,并展示如何在模板中使用循环来显示列表数据。

helloworld.ftl

FreeMarker Template example: ${message}  

=======================
===  County List   ====
=======================
<#list countries as c>
	${c_index + 1}. ${c}
</#list>

public class FTLHelloWorld {
	
	public static void main(String[] args) {

		Configuration cfg = new Configuration();
		try {
			
			Template template = cfg.getTemplate("src/helloworld.ftl");
			
			// Build the data-model
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("message", "Hello World!");

			//List parsing 
			List<String> countries = new ArrayList<String>();
			countries.add("India");
			countries.add("United States");
			countries.add("Germany");
			countries.add("France");
			
			data.put("countries", countries);

			
			// Console output
			Writer out = new OutputStreamWriter(System.out);
			template.process(data, out);
			out.flush();

			// File output
			Writer file = new FileWriter (new File("C:\\FTL_helloworld.txt"));
			template.process(data, file);
			file.flush();
			file.close();
			
			
			
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TemplateException e) {
			e.printStackTrace();
		}
	}
}
输出:

FreeMarker Template example: Hello World!  


=======================
===  County List   ====
=======================
1. India
2. United States
3. Germany
4. France

Thus note how we passed data from Java to FTL and the same get painted. The ${message} got replaced with the message that we populated in Java. Also notice how we passed a country List<String> through Java and inside FTL we used <#list> </#list> to display its values.

原文:http://viralpatel.net/blogs/freemaker-template-hello-world-tutorial/

eclipse工程源代码:http://pan.baidu.com/share/link?shareid=1858728828&uk=3878681452

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值