簡體   English   中英

Thymeleaf - 在 Javascript 代碼中迭代模型屬性

[英]Thymeleaf - Iterating over a model attribute inside Javascript code

我正在嘗試編寫一些需要使用模型屬性的 Javascript 代碼。 這是我定義腳本標簽的方式:

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

    //need some loops

    /*]]>*/
</script>

我需要做的是,使用腳本內模型屬性的each迭代。 到目前為止,我無法用th:each做到這一點。 任何幫助表示贊賞。

我想您需要將模型 attrubite 包裹在雙括號中,如下所示: [[${modelAttribute}]] Thymeleaf 文檔的腳本內聯部分可以提供一些幫助: 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>

你也可以這樣做,我猜這是最緊湊的:

在您的@Controller

model.addAttribute("items", new String[] { "item1", "item2", "item3" });

在您的模板中:

<script type="text/javascript" th:inline="javascript">

var items = [];

/*[# th:each="n : ${items}"]*/

items.push("[(${n})]");

/*[/]*/

</script>

此處解釋了其他有用的內容: [MAJOR FEAT] 文本模板模式的新語法 #395

Thymeleaf 3 -> 見 yglodt 答案

如果您堅持使用Thymeleaf 2並且您的模型屬性很復雜(例如 Maxime Laval 的情況),我最終會遍歷腳本:

<script th:inline="javascript">
  var dataLayer = [];
</script>
<script th:each="item:${items}" th:inline="javascript">
  dataLayer.push({'attr1':item.attr1, 'attr2':item.attr2, 'attr3':item.attr3});
</script>
<script th:inline="javascript">
  console.log(dataLayer); // do whatever you want with dataLayer...
</script>

不是很好,但我找不到更好的谷歌分析。

通過添加/*[[${name}]]*/

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

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

    /*]]>*/
</script>

thymeleaf 將對象轉換為腳本標簽內的 javascript 變量,因此可以使用 javascript 代碼訪問屬性。 無需擔心:

     <script type="text/javascript" th:inline="javascript">
                            /*<![CDATA[*/
                            //the list converts as a javascript object
                            var availableTypes = /*[[${dataList}]]*/;
                            console.log(availableTypes);
                            /*]]>*/
     </script>

在此處輸入圖片說明

如果您堅持使用 Thymeleaf 2,另一種方法是在您的 Script-Tag 中濫用“th:block”-Element

<script type="text/javascript">
        var arrayOfIds= [
        <th:block th:each="element: ${list}" th:inline="text">[[${element.Id}]],</th:block>
            -1 
        ];
        arrayOfIds.pop(); // Remove the superflous last Element
    </script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM