gpt4 book ai didi

html - 用 thymeleaf 添加条件属性

转载 作者:可可西里 更新时间:2023-11-01 13:09:08 32 4
gpt4 key购买 nike

我有一个 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/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com