Thymeleaf和Spring Boot,如何构建assets文件夹以在运行时和设计时查看html

问题描述 投票:2回答:1

我有一个Spring Boot 2项目并使用Thymeleaf模板引擎。文件夹结构是:

main\
  resources\
    static\
      assets\
        css\
          my.css
        js\

    templates\
      index.html

(1)如果我在index.html中将my.css称为../static/assets/css/my.css,我可以直接在浏览器中查看index.html(file:/// path / to / main / resources / templates / index.html)但如果我在JetBrains IDEA中运行项目,并将其作为http://localhost:8080/浏览,则浏览器控制台告诉找不到my.css。

(2)如果我在index.html中将my.css作为assets / css / my.css引用,当我直接在浏览器中查看index.html时(file:///path/to/main/resources/templates/index.html )浏览器告诉找不到my.css,但是如果我在JetBrains IDEA中运行项目,并将其作为http://localhost:8080/浏览,浏览器视图就可以了。

因为Thymeleaf网站表示它对程序员和设计师的设计时间,运行时间和合作都很友好,那么谁能告诉我如何构建我的静态资源和html模板文件夹关系来实现这个目标呢?先谢谢了!

java spring-boot thymeleaf
1个回答
5
投票

在Spring引导中,静态文件从位置src/main/resources/static提供,并且可以在应用程序URL的根目录下获得。例如,如果你有src/main/resources/static/assets/css/my.css,那么当你运行应用程序时,它可以在http://localhost:8080/assets/css/my.css位置获得。

因此,您可以将其包含在index.html中,如下所示:

<link rel="stylesheet" href="../static/assets/css/my.css" 
    th:href="@{/assets/css/my.css}" />

这样,当您在浏览器中打开index.html时,它将使用href检测CSS,当您通过服务器启动它,即运行应用程序并在浏览器中打开它,然后Thymeleaf将自称th:href。所以它适用于这两种情况。

© www.soinside.com 2019 - 2024. All rights reserved.