【问题标题】:Thymeleaf fragment: passing form field name as parameterThymeleaf 片段:将表单字段名称作为参数传递
【发布时间】:2020-06-02 10:08:04
【问题描述】:

我正在尝试将表单输入提取为我的 Spring Boot + Thymeleaf 应用程序中的页面片段。

我正在做这样的事情:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>form controls</title>
</head>
<body>
<div class="form-group" th:fragment="text-input (fieldName, fieldLabel)">
    <label th:text="${fieldLabel}">label</label>
    <input th:field="*{${fieldName}}" type="text" class="form-control"/>
    <div th:if="${#fields.hasErrors('${fieldName}')}">
        <span th:errors="*{${fieldName}}" class="text-danger"></span>
    </div>
</div>
</body>
</html>

我就是这样使用片段的:

<div th:replace="form-controls :: text-input (fieldName='firstName', fieldLabel='Name')">

但是我收到了这个错误:

org.springframework.beans.NotReadablePropertyException: Invalid property '${fieldName}' of bean class [my.app.Dto]: Bean property '${fieldName}' is not readable or has an invalid getter method

所以参数fieldName没有正确解析...

我的代码有问题吗?是否可以在 Thymeleaf 中实现类似于我的片段的东西?

【问题讨论】:

    标签: spring-boot thymeleaf


    【解决方案1】:

    我的问题的解决方案是:Thymeleaf expression preprocessing

    预处理是在正常表达式之前执行的表达式,它允许修改最终将被执行的表达式。

    所以,要修复fieldName 分辨率,我必须用双下划线包围每个${fieldName} exp:

    <div class="form-group" th:fragment="text-input (fieldName, fieldLabel)">
        <label th:text="${fieldLabel}">label</label>
        <input th:field="*{__${fieldName}__}" type="text" class="form-control"/>
        <div th:if="${#fields.hasErrors(fieldName)}">
            <span th:errors="*{__${fieldName}__}" class="text-danger"></span>
        </div>
    </div>
    

    【讨论】:

    • 如果您愿意,您应该可以将${#fields.hasErrors('__${fieldName}__')} 更改为${#fields.hasErrors(fieldName)}。你是对的,你必须对其他部分使用预处理。
    • @Metroids 是的,你是对的!我更新了答案。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2017-05-20
    • 2013-05-26
    • 1970-01-01
    • 1970-01-01
    • 2020-12-31
    • 1970-01-01
    • 1970-01-01
    • 2014-05-15
    相关资源
    最近更新 更多