基于maven,web项目 如果要想使用beetl模板引擎,则首先要在项目的pom.xml中加入依赖文件
<dependency
>
<groupId
>com.ibeetl
</groupId
>
<artifactId
>beetl
</artifactId
>
<version
>2.9.3
</version
>
</dependency
>
资源模板加载器,最大的误区就是模板路径不对,不知道在哪找,下面就让我用示例来说明一下吧。
一、字符串资源模板加载器
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
);
字符串资源模板加载器里面的字符串可以写在项目里。
二、文件资源模板加载器
String root
= System
.getProperty("user.dir")+File
.separator
+"template";
FileResourceLoader resourceLoader
= new FileResourceLoader(root
,"utf-8");
Configuration cfg
=Configuration
.defaultConfiguration();
GroupTemplate gt
= new GroupTemplate(resourceLoader
, cfg
);
Template t
= gt
.getTemplate("/s01/test.html");
t
.binding("title","This is a test template Email.");
t
.binding("name", "beetl");
String str
= t
.render();
System
.out
.println(str
);
resp
.getOutputStream().write(str
.getBytes());
s01/test.html文件内容。
<!DOCTYPE html
>
<html>
<head>
<meta charset
="UTF-8">
<title>$
{title
}</title
>
</head
>
<body>
$
{name
}
</body
>
</html
>
文件资源模板加载器的模板文件位于安装eclipse软件的位置,我这里是D盘下D:\software\eclipse\template; 当然可以修改路径,不过按上面的字符串输出的文件位置为安装eclipse软件的位置。这里需要自己创建template文件夹。
三、classpath资源模板加载器
ClasspathResourceLoader resourceLoader
= new ClasspathResourceLoader();
Configuration cfg
= Configuration
.defaultConfiguration();
GroupTemplate gt
= new GroupTemplate(resourceLoader
, cfg
);
Template t
= gt
.getTemplate("/template/index.html");
t
.binding("name", "beetl");
t
.binding("title", "test beetl");
String str
= t
.render();
System
.out
.println(str
);
t
.renderTo(resp
.getWriter());
classpath资源模板加载器的模板位置位于src/main/resources下面,需要自己创建以下目录/template/index.html。
四、WebApp资源模板加载器
WebAppResourceLoader resourceLoader
= new WebAppResourceLoader(this.getServletContext().getRealPath("/"),
"UTF-8");
Configuration cfg
= Configuration
.defaultConfiguration();
GroupTemplate gt
= new GroupTemplate(resourceLoader
, cfg
);
Template t
= gt
.getTemplate("/template/s01/hello.html");
t
.binding("name", "beetl");
t
.binding("title", "test beetl");
t
.renderTo(resp
.getWriter());
WebApp资源模板加载器的模板位置位于webapp目录下,和WEB-INF同级目录.即src/main/webapp。
这些模板加载器可以写在servlet里面。