【问题标题】:Add conditional attribute with thymeleaf用百里香添加条件属性
【发布时间】:2015-03-15 05:04:24
【问题描述】:

我有一个百里香片段来创建输入字段,例如:

<div th:fragment="formField">
        <input th:type="${type}" th:errorclass="field_error" th:field="*{__${field}__}" th:placeholder="#{__${placeholder}__}" />
</div>

这个片段是例如像这样使用:

<div th:replace="fragments :: formField (type='password', field='password', placeholder='resetPassword.form.password')">

现在应该根据片段的参数将自动对焦属性添加或不添加到输入字段。使用片段,例如像这样应该添加自动对焦属性:

<div th:replace="fragments :: formField (type='password', field='password', placeholder='resetPassword.form.password', autofocus='autofocus')">

我找不到根据片段参数有条件地将 autofocus 属性添加到输入标记的方法。我尝试使用 th:attr 但总是出现语法错误。

有没有办法用百里香有条件地创建html属性?

【问题讨论】:

  • 你试过在html中声明autofocus字段吗(第一个代码sn-p)其他字段都被删除了。另一个建议,您可以尝试 thymeleaf 中的 th:with 属性
  • th:with 只允许你定义变量。
  • fixed-value-boolean-attributes 有一些特殊属性,它允许您根据

标签: html thymeleaf


【解决方案1】:

我猜问题是如果你在片段中声明附加参数 - 你需要传递它。因此,您可以传递 autofocus 或空值 ('') 并使用 Thymeleaf 处理检查。

例如,您调用:

<div th:replace="fragments :: formField (type='password', field='password', 
     placeholder='resetPassword.form.password', autofocus='')">

然后处理它:

<div th:fragment="formField">
    <input th:if="${!autofocus.isEmpty()}" th:type="${type}"
           th:errorclass="field_error" th:field="*{__${field}__}"
           th:placeholder="#{__${placeholder}__}" autofocus="true"/>
    <input th:if="${autofocus.isEmpty()}" th:type="${type}"
           th:errorclass="field_error" th:field="*{__${field}__}"
           th:placeholder="#{__${placeholder}__}"/>
</div>

或者:

<div th:fragment="formField" th:switch="${autofocus}">
    <input th:case="'autofocus'" th:type="${type}"
           th:errorclass="field_error" th:field="*{__${field}__}"
           th:placeholder="#{__${placeholder}__}" autofocus="true"/>
    <input th:case="*" th:type="${type}" th:errorclass="field_error"
           th:field="*{__${field}__}"
           th:placeholder="#{__${placeholder}__}"/>
</div>

但我猜詹姆斯评论使用 th:autofocus 将是最好的解决方案:

<div th:fragment="formField">
        <input th:type="${type}" th:errorclass="field_error" 
               th:field="*{__${field}__}" th:placeholder="#{__${placeholder}__}" 
               th:autofocus="${!autofocus.isEmpty()}" />
</div>

在所有情况下,您仍然需要传递 autofocus="autofocus"autofocus="" 作为参数。

【讨论】:

  • 我想避免有两个完全相同的 字段,它们只是在 autofocus 属性上有所不同。
【解决方案2】:

我认为对于片段来说这是一项过于复杂的任务。我用方言解决了这样的问题。见我的questionsolution

【讨论】:

    猜你喜欢
    • 2018-02-03
    • 1970-01-01
    • 1970-01-01
    • 2014-01-07
    • 1970-01-01
    • 2021-08-01
    • 2019-12-03
    • 2015-06-16
    • 1970-01-01
    相关资源
    最近更新 更多