type cast in EL expressions using Thymeleaf

大憨熊 提交于 2019-12-11 07:05:00

问题


How can I convert object types within EL expressions? Thymeleaf engine doesn't seem to understand something like this:

<span th:text="${((NewObjectType)obj).amount"></span>

Thanks.

Update:

Class hierarchy in which I store data. They are used to populate the HTML table.

public class RootBase implements Serializable {
    ...
}

public class ColBase<T extends RootBase> implements Serializable {

    private ArrayList<T> internalList;

    public int getSize() {
       ...
    }

    public T get(int index) {
       return internalList(index);
    }
}

public class Row extends RootBase {
    ...
}

public class Rows extends ColBase<Row> {
    ...
}

Controller:

Rows rowsColObj = xxxJaxProxyService.getRows();
model.addAttribute("rows", rowsColObj);

View:

<table style="width:100%; border:solid 1px" th:if="${statement}">
  <thead>
    <tr>
      <th style="text-align: left">#</th>
      <th style="text-align: left">Amount</th>
    </tr>
  </thead>
  <tbody th:object="${rows}">
    <tr th:each="index : *{#numbers.sequence(0, size - 1)}" th:with="entry=${#object.get(index)}">
      <td th:text="${index} + 1">1</td>
      <td th:text="${entry.amount}">0</td>
    </tr>
  </tbody>
</table>

回答1:


Can you wrap the list in your own model? Part of the value proposition of SpringMVC and Thymeleaf is to remove the application logic from the view layer. Casting is application logic and should be done within the Controller or if you must...the Model. So if might look like this:

/**
 * Custom model for attributes displayed on the page.
 */    
MyPageModel
    List<TableRows> tableRows;
    public List<TableRows> getTableRows(){...}
    ...

Next, add the model within the controller method. And here is how it might be used in a template to bind the model to the html table:

<table>
    <tr th:each="tableRow : ${model.tableRows}">
        <td class="date" th:text="${tableRow.amount}">$103</td>
    </tr>
    <tr th:unless="*{tableRow}">
        <td colspan="3">No amounts available</td>
    </tr>
</table>


来源:https://stackoverflow.com/questions/16707961/type-cast-in-el-expressions-using-thymeleaf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!