[英]Thymeleaf evaluate nested attribute in Javascript
我一直在嘗試通過JavaScript在會話中存儲的對象上訪問某個變量。 不幸的是,如果該對象不存在,顯然我會在未知屬性上收到SpelEvaluation異常。
例如:
${session.foo} // works
if(false){
${session.foo.bar} // does not work, foo is null. Will be evaluated anyway -> exception
}
該對象在我的項目中全局使用,因此捕獲Exception對我來說並不是一個切實可行的選擇,因為我必須在每個映射上都進行操作。
因此,我嘗試將腳本的那部分放在外部.js文件中,並通過jquery $ .getScript包含它。 但是,此文件中任何Thymeleaf代碼的評估失敗。
如果我的方法正確/建議,誰能給我任何有關如何在外部javascript文件中包含Thymeleaf表達式的提示?
注意:為了便於閱讀,省略了[[${foo}]]
括號。
提前致謝
在這個特定問題上沒有找到任何東西,所以我做了這個。
我的布局裝飾器現在包含一個片段,該片段進行條件檢查是否存在基本變量(例如$ {foo}),然后相應地包含子頁面。
樣例代碼:
layoutDecorator.html:
<div layout:fragment="test" th:include="testIncluder:: testFragment">
My Window here.
</div>
testIncluder.html:
<th:block th:switch="${foo}">
<th:block th:case="null">
<!-- safe include here -->
<th:block th:include="safeInclude :: safeFragment"/>
</th:block>
<th:block th:case="!null">
<!-- unsafe include here -->
<th:block th:include="barInclude :: barFragment"/>
</th:block>
</th:block>
barInclude.html:
<p th:text="${foo.bar}"></p>
<script th:inline="javascript">
/*<![CDATA[*/
...
var bar = [[${foo.bar}]];
...
/*]]>*/
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.