簡體   English   中英

Spring Boot + Thymeleaf css 不適用於模板

[英]Spring Boot + Thymeleaf css is not applied to template

我正在評估 Thymeleaf 和 Flying Saucer 以從模板生成 pdf,我在將 css 應用到我的 Thymeleaf 模板時遇到了問題。 我已經在這里這里這里閱讀了相關的問題和答案; 但沒有一個建議的解決方案解決了我的問題。

這是我的資源文件夾的樣子:

在此處輸入圖片說明

所以我使用的是 Spring 將尋找的默認目錄。 這就是我的template.html head 標簽的樣子:

<head>
    <title>Spring Boot and Thymeleaf Example</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <link rel="stylesheet" type="text/css" href="../static/css/style.css" th:href="@{/css/style.css}"/> 
</head>

如果我在template.html內聯我的 css,那么生成的 pdf 文件的樣式將正確(因此我生成 pdf 的方式應該沒有問題)。 但是,當我嘗試鏈接到如上所示的 css 文件時,生成的 pdf 未設置樣式(因此未應用 css)。

最后,我可以在http://localhost:8080/css/style.css訪問我的 css 文件,因此 Spring 提供靜態內容似乎沒有問題。

為了完整起見,這就是我生成 pdf 的方式:

private final SpringTemplateEngine templateEngine;
private final Log log;

@Autowired
public PdfGenerator(SpringTemplateEngine templateEngine) {
    this.templateEngine = templateEngine;
    log = LogFactory.getLog(getClass());
}

public void generate(HttpServletRequest servletRequest, HttpServletResponse servletResponse, ServletContext servletContext) {
    // Parse the pdf template with Thymeleaf
    Locale locale = getLocale(servletRequest);
    WebContext context = new WebContext(servletRequest, servletResponse, servletContext, locale);
    context.setVariable("user", buildDummyUser());
    context.setVariable("discounts", buildDummyDiscounts());
    String html = templateEngine.process("template", context);

    // Create the pdf with Flying Saucer
    try (OutputStream outputStream = new FileOutputStream("generated.pdf")) {
        ITextRenderer renderer = new ITextRenderer();
        renderer.setDocumentFromString(html);
        renderer.layout();
        renderer.createPDF(outputStream);
    } catch (IOException | DocumentException e) {
        log.error("Error while generating pdf", e);
    }
}

我使用WebContext而不是Context ,因為我發現了以下錯誤與Context

org.thymeleaf.exceptions.TemplateProcessingException: Link base "/css/style.css" cannot be context relative (/...) unless the context used for executing the engine implements the org.thymeleaf.context.IWebContext interface

我在這里錯過了什么,為什么我的style.css沒有應用於template.html

我遇到了同樣的問題,我也在嘗試使用 thymeleaf 模板解析器來生成 pdf。 我對 thymeleaf 和 spring 框架做了很多研究,我嘗試了 WebContext,我嘗試了 HttpServletRequest,我嘗試了一些 Spring Thymeleaf 集成解決方案,但它也不起作用。 所以我認為這不是語法錯誤,我最終使用絕對路徑而不是相對路徑。 參考網址

這是我假設的原因,假設我們的資源是在localhost:8080/myapp/css/style.css 請求資源的相對路徑實際上取決於它相對於什么上下文。 例如,一個普通的百里香葉模型 Veiw,它在客戶端的瀏覽器上作為 html 頁面返回,因此這種情況下的上下文將是請求主機名、端口和應用程序上下文(例如:localhost:8080/myapp)。 相對路徑將基於此。 因此,如果相對路徑是 /css/style.css,則上下文 + 相對路徑將是localhost:8080/myapp/css/style.css

與 web 上下文不同,在我們的例子中,離線模板在服務器后端,所以我假設的上下文是服務器運行上下文,這將是本地服務器路徑 + appcontext(例如:D:/myServer/apps/myapp),相對路徑 /css/style.css 將是D:/myServer/apps/myapp/css/style.css ,這是沒有意義的。 為了使用靜態資源,我必須傳遞它的絕對路徑。

我開始使用:

<link rel="stylesheet" type="text/css" th:href="@{http://localhost:8080/myapp/css/style.css}"/>

它工作正常,但如果有多個主機名或服務器在代理上運行,那么這將是一個硬編碼的解決方案。 最好知道用戶請求的真實基本 url 是什么。 所以我們不能真正擺脫 HttpSevletRequest。

這是我的代碼:

1.配置資源處理程序:

@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/css/**")
    .addResourceLocations("classpath:/css/")
            .setCachePeriod(31556926);
}
  1. 從 HttpServletRequest 獲取基本 url,您可以將其注入方法或自動裝配到您的服務類中,或者從 RequestContextHolder 獲取。 我在我的服務類中寫了這個:

     private static String getCurrentBaseUrl() { ServletRequestAttributes sra = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes(); HttpServletRequest req = sra.getRequest(); return req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + req.getContextPath(); }
  2. 這是我在課堂上使用模板引擎的地方:

     Context context = new Context(); context.setVariable("variales", variables); context.setVariable("baseUrl", getCurrentBaseUrl()); String content = springTemplateEngine.process("myTemplate",context);
  3. 在我的模板中,我使用這樣的絕對 css url:

     <link type="stylesheet" th:src="@{|${baseUrl}/css/style.css|}" />

語法看起來不錯,所以問題不在於語法。

此外,您不能在沒有IWebContext接口的情況下使用@{...}語法,因此您會收到此異常。

我有一個類似的問題 - 我的 css 沒有應用於我的模板頁面。

我的問題是 css 文件是 css sass 格式

.table
   margin: 0 0 40px 0

當我將其轉換為普通的 css 格式時

 .table {
  margin: 0 0 40px 0;
  }

有效

我通過更改 href 中的路徑結構解決了這個問題。 我和你有相同的目錄結構(html 文件在模板文檔中,css 文件在靜態文檔中)。

<head>
    <title>Spring Boot and Thymeleaf Example</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <link rel="stylesheet" type="text/css" href="/css/style.css"/> 
</head>

它可能會幫助您將 css 應用到您的 html 頁面。

我找到了一個懶人的方法來解決這個問題。 它的工作原理非常簡單。 “插入”片段只是簡單 HTML 文檔正文中的 CSS 樣式標記。 我把它放在我的目標文件的 HEAD 中,就在我放置 LINK REL 標簽的地方:

<th:block th:insert="std-reports/std-reports-css-fragment.html :: style"></th:block>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM