无法解析为赋值表达式:“${attrs ?: defaultAttrs}”

000*_*000 2 spring spring-mvc thymeleaf spring-boot

以下 thymeleaf 标记缺少什么:

<tr th:fragment="row" th:with="defaultAttrs='placeholder=\'' + ${placeholder} + '\''">                            
    <td>
        <input th:attr="${attrs ?: defaultAttrs}" />
    </td>
    ...
</tr>
Run Code Online (Sandbox Code Playgroud)

来自

<th:block th:include="row::row(attrs='value=\'*{prodName}\', minLength=\'.{2, 16}\', required, title=\'starts with an alphabet 2 and 8\' placeholder=\'Product name\'')" />
Run Code Online (Sandbox Code Playgroud)

这是产生这个错误:

Could not parse as assignation sequence: "${attrs ?: defaultAttrs}"
Run Code Online (Sandbox Code Playgroud)

在一个不相关的注释中,不得不对异常消息进行双重考虑,以了解赋值而不是赋值一词的有趣用法

Ken*_*kov 5

您正在尝试将文本字符串传递给th:attr. Thymeleaf 需要表达式,而不是字符串。下一个示例将不起作用,但这就是您要执行的操作:

<input th:attr="${'placeholder=\'defaultPlaceholder\''}" />
Run Code Online (Sandbox Code Playgroud)

我建议你下一个方法:

<tr th:fragment="row" th:with="defaultPlaceholder='placeholder', defaultMaxlength=10">                            
    <td>
        <input th:attr="placeholder=${placeholder?:defaultPlaceholder},
            maxlength=${maxlength?:defaultMaxlength}" />
    </td>
    ...
</tr>
Run Code Online (Sandbox Code Playgroud)

它看起来更长,但可以让您更好地控制管理属性。


更新:如果您更喜欢在一个字符串变量中传递所有属性,您可以使用 Thymeleaf 的预处理。例如,下一个代码是您将如何在页面中使用片段:

<div th:include="fragment :: row(attrs='value=\'*{prodName}\', minLength=\'.{2, 16}\', 
    required=true, title=\'starts with an alphabet 2 and 8\', placeholder=\'Product name\'')">
Run Code Online (Sandbox Code Playgroud)

然后你的片段将是这样的:

<div th:fragment="row"> 
    <div th:with="defaults='placeholder=\'placeholder\', maxlength=10'" th:remove="tag">
        <tr>                            
            <td>
                <input th:if="${attrs!=null}" th:attr="__${attrs}__"/>
                <input th:if="${attrs==null}" th:attr="__${defaults}__"/>
            </td>
            ...        
        </tr>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

说明:

  • 片段的主标签不会包含在结果页面中。所以,不要用<tr>作主标签。相反,换行<tr><div>.
  • 传递给片段的参数将覆盖片段th:with主标记中声明的所有变量。因此,如果您想将任何参数传递给片段,请不要th:with在片段的主标记中声明right。做片段的主体。
  • 如果你不需要在结果页面输出一些标签,只需使用th:remove attribute。此属性允许您删除片段的部分。在这个例子中,我们使用了 second<div>来声明th:with,我们不需要<div>在结果页面中使用它。

您的attr参数有误th:include。因为属性是一对名称和值,所以不能只指定required. 你必须写:required=true。另一个错误:您在title和之间错过了逗号placeholder。正确的字符串应该是下一个:

<th:block th:include="row::row(attrs='value=\'*{prodName}\', minLength=\'.{2, 16}\', 
    required=true, title=\'starts with an alphabet 2 and 8\', placeholder=\'Product name\'')" />
Run Code Online (Sandbox Code Playgroud)