You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

传递Thymeleaf片段作为参数时出现选择器语法错误,求排查

问题

我想给所有页面做个共享模板,所有页面带绿色框架,首页额外加蓝色框架。于是写了fragments/whole_page.html包含whole_page片段,在pages/index.html里用~{::index_page_content}作为参数调用这个片段,但请求页面时控制台报错:

java.lang.IllegalArgumentException: Invalid syntax in selector "whole_page(~{ :: #indexPageContent}": selector does not match selector syntax: ((/|//)?selector)?([@attrib="value" ((and|or) @attrib2="value")?])?([index])?

相关代码如下:

控制器代码

//controllers/TaskController.java
@Controller
@RequiredArgsConstructor
public class TaskController {
    private final TasksService tasksService;

    @GetMapping("/")
    public String index(Model model) {
        model.addAttribute("tasks", tasksService.getAllTasks());
        return "pages/index";
    }
}

首页模板(templates/pages/index.html)

<!DOCTYPE html>
<html
        lang="en"
        xmlns:th="http://www.thymeleaf.org"
        th:replace="~{ fragments/whole_page.html :: whole_page(~{ :: index_page_content}}"
>
<div
    th:fragment="index_page_content"
    style="margin: 5px; padding: 5px; border: 2px solid blue;"
>
    <p th:if="${tasks.size() == 0}">
        No tasks stored at the moment
    </p>
    <p th:if="${tasks.size() > 0}">
        There are <th:block th:text="${tasks.size()}" /> tasks stored at the moment
    </p>
</div>
</html>

共享片段模板(templates/fragments/whole_page.html)

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" th:fragment="whole_page(content)">
<head>
    <meta charset="UTF-8" />
    <title>Title</title>
</head>
<body>
    <div style="margin: 5px; padding: 5px; border: 2px solid green;">
        <th:block th:replace="${content}" />
    </div>
</body>
</html>
问题分析与解决

错误出在首页模板的th:replace语法上——你少写了一个闭合的括号。

原代码里的:

th:replace="~{ fragments/whole_page.html :: whole_page(~{ :: index_page_content}}"

最后面的~{ ... }没有闭合,应该补上一个),修正后:

th:replace="~{ fragments/whole_page.html :: whole_page(~{ :: index_page_content})}"

另外错误信息里提到的#indexPageContent和你代码里的index_page_content不一致,这是Thymeleaf解析错误语法时的误报,只要修正括号闭合问题,这个错误就会消失。

修正后的首页模板代码:

<!DOCTYPE html>
<html
        lang="en"
        xmlns:th="http://www.thymeleaf.org"
        th:replace="~{ fragments/whole_page.html :: whole_page(~{ :: index_page_content})}"
>
<div
    th:fragment="index_page_content"
    style="margin: 5px; padding: 5px; border: 2px solid blue;"
>
    <p th:if="${tasks.size() == 0}">
        No tasks stored at the moment
    </p>
    <p th:if="${tasks.size() > 0}">
        There are <th:block th:text="${tasks.size()}" /> tasks stored at the moment
    </p>
</div>
</html>

内容的提问来源于stack exchange,提问作者Northsoft

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 15:33:43