zl程序教程

您现在的位置是:首页 >  其他

当前栏目

【转载】FreeMarker解析字符串模板

模板 解析 字符串 转载 freemarker
2023-09-11 14:21:14 时间
private static final String DEFAULT_TEMPLATE_KEY = "_default_template_key"; private Map templates = new HashMap(); public StringTemplateLoader(String defaultTemplate) { if (defaultTemplate != null !defaultTemplate.equals("")) { templates.put(DEFAULT_TEMPLATE_KEY, defaultTemplate); public void AddTemplate(String name, String template) { if (name == null || template == null || name.equals("") || template.equals("")) { return; if (!templates.containsKey(name)) { templates.put(name, template); public void closeTemplateSource(Object templateSource) throws IOException { public Object findTemplateSource(String name) throws IOException { if (name == null || name.equals("")) { name = DEFAULT_TEMPLATE_KEY; return templates.get(name); public long getLastModified(Object templateSource) { return 0; public Reader getReader(Object templateSource, String encoding) throws IOException { return new StringReader((String) templateSource); }

 

 

 

测试类:

package cn.com.aweb.vote.test.other;

import java.io.StringWriter;

import java.util.HashMap;

import java.util.Map;

import freemarker.template.Configuration;

import freemarker.template.Template;

public class Test{

 public static void main(String[] args) throws Exception {

 Configuration cfg = new Configuration(); 

 cfg.setTemplateLoader(new StringTemplateLoader("hello:${user}")); 

 cfg.setDefaultEncoding("UTF-8"); 

 Template template = cfg.getTemplate(""); 

 Map root = new HashMap(); 

 root.put("user", "lunzi"); 

 StringWriter writer = new StringWriter(); 

 template.process(root, writer); 

 System.out.println(writer.toString()); 

}
附件是 freemarker 学习 pdf

字符串模板浅析 虽然现在有各种前端框架来提高开发效率,但是在某些情况下,原生 JavaScript 实现的组件也是不可或缺的。例如在我们的项目中,需要给业务方提供一个通用的支付组件,但是业务方使用的技术栈可能是 Vue、React 等,甚至是原生的 JavaScript。
JavaWeb实现导出Word文档到本地(使用FreeMarker模版引擎实现) http://freemarker.org/ Freemarker官网,英文,可以用谷歌浏览器的自动翻译,英文水平高的忽略这句。。 简单来说:FreeMarker是一个模板引擎,一个基于模板生成文本输出的通用工具,使用纯Java编写。
freemarker语法 freemarker中显示某对象使用${name}.   但如果name为null,freemarker就会报错。如果需要判断对象是否为空: #if name?? /#if   当然也可以通过设置默认值${name! }来避免对象为空的错误。如果name为空,就以默认值( ! 后的字符)显示。   对象user,name为user的属性的情况,user,