【问题标题】:Thymeleaf check if variable equals a numberThymeleaf 检查变量是否等于数字
【发布时间】:2020-01-05 20:39:29
【问题描述】:

我有以下 Thymeleaf 代码,如果 taxHistory.landValue 等于 0 则打印“--”,如果 taxHistory.landValue 大于 0 则打印实际值

<td th:if"${taxHistory.landValue==0}" th:text="--"></td>
<td th:unless="${taxHistory.landValue>0}" th:text="|${taxHistory.landValue}|"></td>

但是我收到以下错误

org.thymeleaf.exceptions.TemplateProcessingException: Could not parse as expression: "0}" 

在 Thymeleaf 中这样做的正确方法是什么?

【问题讨论】:

    标签: thymeleaf


    【解决方案1】:

    有多种方法可以做到这一点,但如果您想要的条件不匹配,您可以使用三元运算符并打印您的字符串:

    <td th:text="${taxHistory.landValue &gt; 0 ? taxHistory.landValue : '--' }">[taxHistory.landValue]</td>
    

    您可以使用&amp;gt; 表示法来保留HTML formed properly。这假设一个负值也会打印你的字符串(你没有提到那种不寻常的情况下的行为)。

    【讨论】:

    • 很好用,你知道我们如何将字符串添加到&gt;[taxHistory.landValue]&lt; 吗?我想在它后面加一个美元符号。我手动添加了它,但它没有显示在网页上。
    • 看看这篇文章(以及我的更新答案):stackoverflow.com/questions/14160304/…
    • 请注意,如果您刚刚在浏览器中打开 HTML 页面,您在评论中的内容是默认值。如果页面在服务器/容器上提供,则不会显示。最佳做法是添加此默认值,这样您就可以在不提供页面的情况下查看页面的外观。这对 UI 设计师来说很有效。
    • 这样的东西有用吗? pastebin.com/kJmUg1NV 我正在尝试将单行 if 语句的结果放入变量中,然后内联打印。不过现在它给出了一个错误。
    • 在前一种情况下,像这样(未经测试):&lt;td th:with="totalAssessment=${taxHistory.landValue + taxHistory.additions}" th:text=${totalAssessment &amp;gt; 0 ? #numbers.formatCurrency(result) : '--' }"&gt;[total assessment]&lt;/td&gt;
    猜你喜欢
    • 2015-02-04
    • 2012-09-21
    • 2015-05-01
    • 1970-01-01
    • 2012-10-16
    • 1970-01-01
    • 2021-12-11
    • 1970-01-01
    • 2019-11-17
    相关资源
    最近更新 更多