使用Thymeleaf在EL表达式中强制类型转换 [英] type cast in EL expressions using Thymeleaf

查看:1227
本文介绍了使用Thymeleaf在EL表达式中强制类型转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在EL表达式中转换对象类型? Thymeleaf引擎似乎不了解以下内容:

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>

谢谢。

更新:

存储数据的类层次结构。它们用于填充HTML表。

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> {
    ...
}

控制器:

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

查看:

<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>


推荐答案

可以将列表包装在自己的模型中吗? SpringMVC和Thymeleaf的部分价值主张是从视图层删除应用程序逻辑。转换是应用程序逻辑,应在Controller内完成,或者必须在模型中完成。因此,如果看起来像这样:

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(){...}
    ...

接下来,在其中添加模型控制器方法。以下是在模板中将其绑定到html表的方法:

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>

这篇关于使用Thymeleaf在EL表达式中强制类型转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆