【问题标题】:Assign Thymeleaf dialect expression return value to Thymeleaf variable in th:with将 Thymeleaf 方言表达式返回值分配给 th:with 中的 Thymeleaf 变量
【发布时间】:2019-05-15 11:31:21
【问题描述】:

我正在拼命尝试将 Thymeleaf 方言表达式返回值分配给 th:with 属性中的 Thymeleaf 变量。

我想达到这样的目标:

<th:block th:with="foo=${#lists.contains(modelList, modelVariable)}" />

注意:我完全确定我的 #lists.contains 表达式有效,因为我已经在 h1 标记中打印了返回值,并将 true 作为文本返回:

<h1 th:text="${#lists.contains(modelList, modelVariable)}"></h1>

到目前为止,我已经尝试了以下语法,它们都以某种方式给了我解析错误...

没有外部${}:

<th:block th:with="foo=#lists.contains(modelList, modelVariable)" />

带预处理:

<th:block th:with="foo=${__#lists.contains(modelList, modelVariable)__}" />

经过预处理并将其包装在${}

<th:block th:with="foo=${__${#lists.contains(modelList, modelVariable)}__}" />

为什么这些表达式中的任何一个都有效?

我做错了什么还是 Thymeleaf th:with 表达式的错误/不可能?

谢谢。

【问题讨论】:

    标签: java spring-boot spring-mvc thymeleaf


    【解决方案1】:

    th:with 表达式本身没有任何问题。但是,使用th:with 创建的变量仅适用于子标签。您的th:block 立即关闭,因此foo 立即超出范围,没有任何东西可以访问它。例如,这会起作用:

    <th:block th:with="foo=${#lists.contains(modelList, modelVariable)}">
        <div th:text="${foo}" />
    </th:block>
    

    但这不是:

    <th:block th:with="foo=${#lists.contains(modelList, modelVariable)}" />
    <div th:text="${foo}" />        
    

    没有办法像这样定义一个全局变量(我想除了放在&lt;html /&gt;标签上)。

    【讨论】:

    • 不可能...我知道 :( 我不知道为什么我关闭了标签。我稍后会尝试并告诉你你是否正确。我确定这就是问题所在. 谢谢!
    • 你完全正确!现在它工作正常,再次感谢! :)
    猜你喜欢
    • 2017-02-18
    • 2017-11-08
    • 2018-11-29
    • 1970-01-01
    • 2015-12-18
    • 2015-12-31
    • 2019-04-19
    • 2019-09-06
    • 1970-01-01
    相关资源
    最近更新 更多