beetl模板引擎基礎使用方法

beetl模板引擎和freemarker使用方法基本上大同小異,但總的來說都很簡單,其實其主要解決問題就是替換模板變量,下面我們來看一下一些基本的使用技巧
1、首先,當然是要引入依賴包

        <dependency>
            <groupId>com.ibeetl</groupId>
            <artifactId>beetl-framework-starter</artifactId>
            <version>1.1.55.RELEASE</version>
        </dependency>

2、然後就是編寫基礎代碼如下

public class BeetlTest {
    public static void main(String[] args) throws IOException {
        /*1、創建資源加載器*/
        final StringTemplateResourceLoader loader = new StringTemplateResourceLoader();
        /*2、創建默認配置*/
        final Configuration config = Configuration.defaultConfiguration();
        /*3、創建模板引擎*/
        final GroupTemplate groupTemplate = new GroupTemplate(loader, config);
        /*4、創建模板內容,${title}和${content}便是佔位符*/
        String testTemp = "<!DOCTYPE html>\n" +
                "<html lang=\"en\">\n" +
                "<head>\n" +
                "    <meta charset=\"UTF-8\">\n" +
                "    <title>${title}</title>\n" +
                "</head>\n" +
                "<body>\n" +
                "    ${content}\n" +
                "</body>\n" +
                "</html>";
        /*5、加載模板,綁定替換參數*/
        final Template template = groupTemplate.getTemplate(testTemp);
        template.binding("title","我是標題");
        template.binding("content","內容就是我");
        /*此處如果變量太多可以使用map形式傳參*/
//        final HashMap<String, String> map = new HashMap<>();
//        map.put("title", "我是標題map");
//        map.put("content", "內容就是我map");
//        template.binding(map);
        /*6、渲染*/
        final String render = template.render();
        System.out.println(render);
    }
}

打印結果如下:
在這裏插入圖片描述
3、然後就是一些基本的if和for循環的使用,和freemark基本也是一樣
使用beetl的模板語法兩個百分號

for循環
    <%
    for(entry in map){
        print(entry.key+"::"+entry.value);
    }
    %>

示例:
在這裏插入圖片描述

if判斷
    <%
    if(temp=="aaa"){
        print("我是aaa");
    } else if(temp=="bbb"){
        print("我是bbb");
    } else {
        print("我是其他的");
    }
    %>

示例:
在這裏插入圖片描述
以上就是一些基本使用技巧了,滿足日常的一些字符串替換還是可以的

發佈了51 篇原創文章 · 獲贊 16 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章