2

I'm adding an attribute to my ModelAndView in spring and after this i forwarding it to my thymeleaf view.

In the view i have the following code:

<script th:inline="javascript">
        /*<![CDATA[*/
            var applicationName = /*[[${T(com.sample.constants.ApplicationConstants).MODEL_ATTR_COLLECTED_VALUES}]]*/ "Test";
            var collectedValueJson = [[${collectedValues}]];
            console.log(collectedUserJson);
        /*]]>*/
</script>

Result from this is

var applicationName = 'collectedValues';
var collectedUserJson = '[{\"givenname\":\"Muster\",\"surname\":\"Peter\"}]';

That's fine. Now my wish for this is, that i can take the var application and access with this variable the modelattribute, but that's not working.

Result is this:

var tmp2 = ${applicationName};

An other try was, that i have access to the modelattribute with the syntax /*[[ ]]*/ from the first try:

var applicationName = ${/*[[${T(com.sample.constants.ApplicationConstants).MODEL_ATTR_COLLECTED_VALUES}]]*/};

But result will be:

var tmp = ${'collectedValues'

i have no idea what can i try.

Any other suggestions?

Thank's in advance.

1

3 Answers 3

5

There is a workaround worth mentioning: Write out the attribute to

<span id="myvar" th:text="${attributeName}"></span>

and then read it in with JavaScript using

document.getElementById("myvar").value

or some similar jQuery call:

$('#myvar').text() 
Sign up to request clarification or add additional context in comments.

1 Comment

spans value may give undefined. you can use span.innerHTML
3

You can:

<span id="span_id" style="display: none;" th:text="${attributeName}"></span>

and then in your Javascript:

document.getElementById("span_id").innerHTML

Comments

2

there is no way you can access model atributes hence they are on server side and they where lost when rendering jsp into HTML

4 Comments

This is false as Spring Boot provides with the model to pass the atributes so it can be rendered by Thymeleaf.
@CarlosLópezMarí does Thymeleaf not resolve the view at server side itself
@AB It does, but the rendered view can contain any given values. Just as the html.
He doesn't need to do it after rendering if I understood correctly

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.