我有一个thymeleaf片段来创建输入字段,比如:

<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')">

现在,应该根据片段的参数将autofocus属性添加到或不添加到输入字段。像这样使用片段应该添加autofocus属性:
<div th:replace="fragments :: formField (type='password', field='password', placeholder='resetPassword.form.password', autofocus='autofocus')">

我找不到基于片段参数有条件地将autofocus属性添加到输入标记的方法。我试过使用th:attr,但总是出现语法错误。
有没有办法用thymeleaf有条件地创建html属性?

最佳答案

我想问题是如果你在片段中声明了额外的参数-你需要传递它。因此,您可以通过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>

但我想james使用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=”作为参数。

关于html - 用 thymeleaf 添加条件属性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27986560/

10-10 15:57