简体   繁体   中英

Thymeleaf evaluate nested attribute in Javascript

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.

Eg:

${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

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 (eg ${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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM