从 Thymeleaf 中的模型对象设置 CSS 变量 [英] Set CSS variables from model object in Thymeleaf

查看:19
本文介绍了从 Thymeleaf 中的模型对象设置 CSS 变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 Thymeleaf 模板的样式标签内设置 CSS 颜色变量.颜色值来自模型对象.我还想应用默认颜色,以防模型属性不存在.

I'm setting CSS color variables inside a style tag in a Thymeleaf template. The color values are coming from the model object. I also want to apply a default color, in case the model attirbute is not there.

但是当我渲染模板时,Thymeleaf 不会计算表达式,而是将整个表达式指定为字符串文字,而不是颜色值.

But when I render the template, Thymeleaf doesn't evaluate the expression, but assigns the entire expression as a string literal, instead of the color value.

下面是我的风格标签.我在 Apache Freemarker 中做了同样的事情,它运行良好.我对 Thymeleaf 还很陌生,我应该在这里做些什么不同的事情?

Below is my style tag. I've done the same thing in Apache Freemarker, and it worked fine. I'm pretty new to Thymeleaf, what should I do differently here?

<style>
  :root {
    --primary-color: ${brandingConfig?.themeConfig?.primaryColor} ?: '#633EA5';
    --secondary-color: ${brandingConfig?.themeConfig?.secondaryColor} ?: '#E9E6ED';
  }
</style>

推荐答案

如果你想设置 CSS 变量,你应该使用 CSS 内联.

If you want to set CSS variables, you should use CSS inlining.

<style th:inline="css">
  :root {
    --primary-color: [[${brandingConfig?.themeConfig?.primaryColor} ?: '#633EA5']];
    --secondary-color: [[${brandingConfig?.themeConfig?.secondaryColor} ?: '#E9E6ED']];
  }
</style>

通常 Thymeleaf 处理器只计算标签的 th:* 属性中的表达式.但是,如果您在样式标记上设置 th:inline="css",您可以使用 [[...]] 表达式来评估标记内的文本.

Normally the Thymeleaf processor only evaluates expressions in th:* attributes of tags. However, if you set th:inline="css" on your style tag you can use [[...]] expressions to evaluate the text inside a tag.

这篇关于从 Thymeleaf 中的模型对象设置 CSS 变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆