1.2 快速开始
About 449 wordsAbout 2 min
2025-01-24
1.2 快速开始
Beetl的核心是GroupTemplate
,是一个重量级对象,实际使用的时候建议使用单模式创建,创建GroupTemplate需要2个参数,一个是模板资源加载器,一个是配置类,模板资源加载器Beetl内置了6种,分别是:
- StringTemplateResourceLoader:字符串模板加载器,用于加载字符串模板,如本例所示
- FileResourceLoader:文件模板加载器,需要一个根目录作为参数构造,传入getTemplate方法的String是模板文件相对于Root目录的相对路径
- ClasspathResourceLoader:现代web应用最常用的文件模板加载器,模板文件位于Classpath里
- WebAppResourceLoader:用于webapp集成,假定模板根目录就是WebRoot目录,参考web集成章
- MapResourceLoader:可以动态存入模板
- CompositeResourceLoader:混合使用多种加载方式
//初始化代码
StringTemplateResourceLoader resourceLoader = new StringTemplateResourceLoader();
Configuration cfg = Configuration.defaultConfiguration();
GroupTemplate gt = new GroupTemplate(resourceLoader, cfg);
//获取模板
Template t = gt.getTemplate("hello,${name}");
t.binding("name", "beetl");
//渲染结果
String str = t.render();
System.out.println(str);
代码第5行将变量name传入模板里,其值是Beetl
。 代码第6行是渲染模板,得到输出,template提供了多种获得渲染输出的方法,如下
- template.render() 返回渲染结果,如本例所示
- template.renderTo(Writer) 渲染结果输出到Writer里,如果你的Writer是一个FilterWriter,则可把输出保存到文件里
- template.renderTo(OutputStream) 渲染结果输出到OutputStream里
- Beetl 支持为模板自定义定界符和占位符,如本例子采用的默认占位符号
${}
。 后面可以看到,可以定义任意其他符号,比如#{}
或者##
- 如果不想写代码直接体验 Beetl 提供的基本功能,可以使用 http://ibeetl.com/beetlonline/