Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

spring - Thymeleaf - Iterating over a model attribute inside Javascript code

I'm trying to write some Javascript code where I need to use a model attribute. Here is how I define the script tag:

<script type="text/javascript" th:inline="javascript">
    /*<![CDATA[*/

    //need some loops

    /*]]>*/
</script>

What I need to do is, using each iterations over model attributes inside the script. So far I couldn't manage to do this with th:each. Any help is appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I guess you need to wrap your model attrubite in double brackets, like this: [[${modelAttribute}]]. The script inlining section of the Thymeleaf docs can help a bit: http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#script-inlining-javascript-and-dart

<script type="text/javascript" th:inline="javascript">
    /*<![CDATA[*/

    var theList = [[${modelAttribute}]]
    for (i = 0; i < theList.length; i++) {
        doSomething(theList[i]);
    }

    /*]]>*/
</script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...