首页 > 解决方案 > 为什么我的 thymeleaf #strings 不起作用?

问题描述

我正在处理的 html 上有一个表格,对于一列,我想显示最多 30 个字符(因为它可能很长)。下面是我的代码,但它不工作,我不知道为什么。任何建议将不胜感激。先感谢您 :)

<span th:text="${#strings.substring(history.keyword,0,30)} + '…'"></span>

标签: stringsubstringthymeleaf

解决方案


要使这样的事情起作用,您需要考虑那些可能少于 30 个字符限制的字符串。在这种情况下,上述方法将失败(使用 Java ArrayIndexOutOfBoundsException)。

有不同的方法。一种方法是使用 Thymeleaf 的“if/else”语法 ( (if) ? (then) : (else)) 来处理这个问题 - 例如:

<block th:with="kwd=${history.keyword}, len=${#strings.length(history.keyword)}">
    <span th:text=" ( ${len > 30} ) 
          ? ${#strings.substring(kwd,0,30)} + '…'
          : ${kwd}"></span>
</block>

我在上述方法中使用的另一件事是th:with创建 2 个变量:kwd并使lenif/else 语句更具可读性。


推荐阅读