Reputation: 1354
I've been trying to access a certain variable via javascript on an object stored in a session. Unfortunately, if the object is not present, obviously I get a SpelEvaluation exception on the unknown attribute.
E.g.:
${session.foo} // works
if(false){
${session.foo.bar} // does not work, foo is null. Will be evaluated anyway -> exception
}
The object is used globally on my project, so catching the Exception is not really a viable option for me, since I would have to do it on every single mapping.
So I've tried putting that part of my script in an external .js file and include it via jquery $.getScript. But the evaluation for any Thymeleaf code in this file fails.
If my approach is the correct/recommended, can anyone give me any hints on how to include Thymeleaf expressions in an external javascript file?
Note: [[${foo}]]
brackets omitted for readability.
Thanks in advance
Upvotes: 0
Views: 622
Reputation: 1354
Didn't find anything on this particular issue, so I did this instead.
My layout decorator now includes a fragment that does a conditional check if the base variable (e.g. ${foo}) exists and then includes the subpages accordingly.
Sample code:
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>
Upvotes: 1