Thymeleaf 评估 Javascript 中的嵌套属性
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
}
该对象在我的项目中全局使用,因此捕获异常对我来说并不是一个真正可行的选择,因为我必须在每个映射上都这样做。
所以我尝试将脚本的那部分放在外部 .js 文件中,并通过 jquery $.getScript 包含它。但是对该文件中任何 Thymeleaf 代码的评估都失败了。
如果我的方法是 correct/recommended,谁能给我任何关于如何在外部 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>
我一直在尝试通过 javascript 访问存储在会话中的对象上的某个变量。不幸的是,如果该对象不存在,显然我会在未知属性上遇到 SpelEvaluation 异常。
例如:
${session.foo} // works
if(false){
${session.foo.bar} // does not work, foo is null. Will be evaluated anyway -> exception
}
该对象在我的项目中全局使用,因此捕获异常对我来说并不是一个真正可行的选择,因为我必须在每个映射上都这样做。
所以我尝试将脚本的那部分放在外部 .js 文件中,并通过 jquery $.getScript 包含它。但是对该文件中任何 Thymeleaf 代码的评估都失败了。
如果我的方法是 correct/recommended,谁能给我任何关于如何在外部 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>