html - documentacion - thymeleaf print variable
Thymeleaf-Cómo agregar atributos marcados para ingresar condicionalmente (4)
Después de cavar un poco, encontré la solución. Hay th:checked atributo th:checked para ese propósito.
Esto funciona:
<input type="checkbox" name="mycheckbox" th:checked="${flag} ? ''checked''">
Esto falla:
<input type="checkbox" name="mycheckbox" th:checked="${flag} ? ''checked'' : ''''">
Si está checked="" está configurado como componente de input , está marcado como marcado. Este método es válido para atributos personalizados th:attr también. Considere el siguiente ejemplo:
<p th:attr="customattr=${flag}?''attr''></p>
Si la flag es verdadera, se reemplaza por:
<p customattr="attr"></p>
Si la flag es falsa, se reemplaza por:
<p></p>
Como sabe, input componente de input tiene un atributo, que se checked si marca la casilla de verificación como habilitada de forma predeterminada o no.
<input type="checkbox" name="mycheckbox" checked="checked"/>
Para deshabilitar la casilla de verificación de forma predeterminada, se debe declarar la excepción checked . ¿Es posible establecer el atributo checked por una bandera en Thymeleaf?
Ninguna de las soluciones sugeridas funcionó para mí.
Éste funcionó:
th:checked="${#strings.equals(param.myRequestParameterXYZ, ''foobar'')}"
Puede agregar condicionalmente el atributo marcado a la entrada de radio en thymeleaf como se muestra a continuación:
<input type="radio" th:checked="${sales.sales_head.sales_type} == CREDIT" class="sales_type" value="CREDIT" name="sales_type" >
Aquí si sales_type es CREDIT, la radio será revisada. De lo contrario, permanece sin marcar.
Según la documentación oficial de thymeleaf.
http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#fixed-value-boolean-attributes
th:checked se considera como un atributo booleano de valor fijo.
<input type="checkbox" name="active" th:checked="${user.active}" />
Donde user.active debería ser un boolean .
Así que en tu caso debería ser como Andrea mencionó,
<input type="checkbox" name="mycheckbox" th:checked="${flag}" />