猿问

Thymeleaf:将 webjar CSS 文件的内容插入样式标签

在某些情况下,内联 CSS 文件比通过 URL 引用它更受欢迎(例如,在呈现包含所有内容的 HTML 页面时)。该 CSS 文件可能来自 webjar。

我需要什么才能拨打这样的电话:

<style th:insert="/webjars/bootstrap/bootstrap.css"></style>

这是在 spring-boot 环境中运行的,没有任何网络服务器。



大话西游666
浏览 178回答 1
1回答

慕娘9325324

所以我让它与一个特殊的 TemplateResolver 一起工作。它的逻辑类似于 Spring 的WebJarsResourceResolver,并且使用WebJarAssetLocator.public class WebJarTemplateResolver extends ClassLoaderTemplateResolver {&nbsp; &nbsp; private final static String WEBJARS_PREFIX = "/webjars/";&nbsp; &nbsp; private final static int WEBJARS_PREFIX_LENGTH = WEBJARS_PREFIX.length();&nbsp; &nbsp; private final WebJarAssetLocator webJarAssetLocator = new WebJarAssetLocator();&nbsp; &nbsp; @Override&nbsp; &nbsp; protected ITemplateResource computeTemplateResource(IEngineConfiguration configuration, String ownerTemplate, String template, String resourceName, String characterEncoding, Map<String, Object> templateResolutionAttributes) {&nbsp; &nbsp; &nbsp; &nbsp; resourceName = findWebJarResourcePath(template);&nbsp; &nbsp; &nbsp; &nbsp; if (resourceName == null) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return null;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return super.computeTemplateResource(configuration, ownerTemplate, template, resourceName, characterEncoding, templateResolutionAttributes);&nbsp; &nbsp; }&nbsp; &nbsp; @Nullable&nbsp; &nbsp; protected String findWebJarResourcePath(String templateName) {&nbsp; &nbsp; &nbsp; &nbsp; if (!templateName.startsWith(WEBJARS_PREFIX)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return null;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; int startOffset = WEBJARS_PREFIX_LENGTH;&nbsp; &nbsp; &nbsp; &nbsp; int endOffset = templateName.indexOf('/', startOffset);&nbsp; &nbsp; &nbsp; &nbsp; if (endOffset == -1) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return null;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; String webjar = templateName.substring(startOffset, endOffset);&nbsp; &nbsp; &nbsp; &nbsp; String partialPath = templateName.substring(endOffset + 1);&nbsp; &nbsp; &nbsp; &nbsp; return this.webJarAssetLocator.getFullPathExact(webjar, partialPath);&nbsp; &nbsp; }}这通过以下配置集成到应用程序中:@Configurationpublic class ThymeleafConfiguration {&nbsp; &nbsp; private SpringTemplateEngine templateEngine;&nbsp; &nbsp; public ThymeleafConfiguration(SpringTemplateEngine templateEngine) {&nbsp; &nbsp; &nbsp; &nbsp; this.templateEngine = templateEngine;&nbsp; &nbsp; }&nbsp; &nbsp; @PostConstruct&nbsp; &nbsp; public void enableWebjarTemplates() {&nbsp; &nbsp; &nbsp; &nbsp; templateEngine.addTemplateResolver(new WebJarTemplateResolver());&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Java
我要回答