首页 > 解决方案 > Thymeleaf:th:insert 不起作用,而 th:replace 运行良好

问题描述

我正在使用 Spring Boot + Thymeleaf。这是我的pom.xml

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>...</groupId>
    <artifactId>...</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.2.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

项目结构(相关部分):

-src
   -main
      -resources
         -templates
            -fragments
               navbar.html
            home.html

navbar.html我有以下片段:

<nav th:fragment="navbar">...</nav>

home.html我使用上面的片段:

  1. <div th:insert="fragments/navbar :: navbar"></div>
  2. <div th:replace="fragments/navbar :: navbar"></div>

问题是:为什么第一个变体(带有 th:insert)不起作用,而第二个变体(带有 th:replace)工作正常?

PS我已阅读文档并期望以下内容:

<!-- with th:insert -->
<div>
    <nav>...</nav>
</div>

<!-- with th:replace -->
<nav>...</nav>

标签: javathymeleaf

解决方案


推荐阅读