beetl中4种资源模板加载器的用法,模板位置。

mac2024-05-17  33

基于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"; //这是安装eclipse软件的位置,D盘下D:\software\eclipse\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"); //root下的文件 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资源模板加载器

// Classpath资源模板加载器 ClasspathResourceLoader resourceLoader = new ClasspathResourceLoader(); // "template/" //此模板路径为 src/main/resources/template/index.html 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资源模板加载器

// WebApp资源模板加载器 WebAppResourceLoader resourceLoader = new WebAppResourceLoader(this.getServletContext().getRealPath("/"), "UTF-8"); //这是项目保存路径E:\java\eclipse-database\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\mybeetl\ //即在webapp目录下,和WEB-INF同级目录 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里面。

最新回复(0)