Html 使用thymeleaf添加条件属性
我有一个thymeleaf片段来创建输入字段,如:Html 使用thymeleaf添加条件属性,html,thymeleaf,Html,Thymeleaf,我有一个thymeleaf片段来创建输入字段,如: <div th:fragment="formField"> <input th:type="${type}" th:errorclass="field_error" th:field="*{__${field}__}" th:placeholder="#{__${placeholder}__}" /> </div> 例如,该片段的用法如下: <div th:replace="fra
<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,但最终总是出现语法错误
有没有一种方法可以使用thymeleaf有条件地创建html属性?我认为这对于一个片段来说太复杂了。我用方言解决了这个问题。请参阅my和。我想问题在于,如果在片段中声明附加参数,则需要传递它。因此,您可以传递自动对焦或空值(“”),并使用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>
或:
但我想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(第一个代码段)中声明自动聚焦字段,其他字段将被删除。另一个建议是,您可以尝试thymeleafth:with中的
th:with
属性,该属性仅允许您定义变量。有一些特殊属性,允许您设置诸如“自动聚焦”之类的特殊属性基于一个布尔表达式,比如我想要避免两个完全相同的字段,它们只是在自动聚焦属性上不同。
<div th:fragment="formField">
<input th:type="${type}" th:errorclass="field_error"
th:field="*{__${field}__}" th:placeholder="#{__${placeholder}__}"
th:autofocus="${!autofocus.isEmpty()}" />
</div>