0

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

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.