Thymeleaf內聯JS

原理

內聯語法的格式爲:[[${xxxx}]]
內聯語法可以

  • 讀取服務器端變量
  • 調用內置對象的方法等

示例

第一步

創建SpringBoot項目,添加依賴,編寫application.yml,參看博客:SpringBoot 集成Thymeleaf

頁面模板

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <script th:inline="javascript">
            /*<![CDATA[*/
            let user = [[${dept}]];
            let path = [[${#request.getContextPath()}]];
            let cou = [[${#locale.getLanguage()+'_'+#locale.getCountry()}]];
            console.info(user);
            console.info(path);
            console.info(cou)
            /*]]>*/
        </script>
    </body>
</html>
## Controller
@RequestMapping("/inline")
public String inline(Model model) {
    model.addAttribute("dept",new Dept(10,"sales","CHICAGO"));
    model.addAttribute("data", Arrays.asList("aa","bb","cc","dd"));
    return "inline";
}

效果

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章