You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R Shiny中获取bs_theme()的主题颜色代码?

获取Bootstrap主题颜色与转换CSS为R代码

一、获取primary/secondary等主题颜色代码

通过bslib包的bs_theme_get_variables()函数可以直接提取主题中的颜色变量:

library(bslib)

# 初始化你的主题
my_theme <- bs_theme(version = 5, bootswatch = "pulse")

# 获取指定的主题颜色(可添加更多颜色名称)
theme_color_codes <- bs_theme_get_variables(my_theme, c("primary", "secondary"))

# 打印颜色代码
print(theme_color_codes)

运行后会输出类似list(primary = "#5D3FD3", secondary = "#6C757D")的结果,就是对应颜色的十六进制代码。

二、将CSS代码转换为R代码实现

你看到的CSS是Bootstrap的Sass语法,在R Shiny中可以通过两种方式实现:

方式1:直接用Sass语法添加到主题

利用bs_add_rules()将原Sass代码嵌入主题,bslib会自动解析Sass变量:

my_theme <- my_theme |>
  bs_add_rules(
    ".fa-li {
       color: map-get($theme-colors, 'primary');
     }"
  )

# 在Shiny UI中使用这个主题
ui <- fluidPage(
  theme = my_theme,
  # 你的UI内容
)

方式2:用已提取的颜色值设置样式

先获取颜色代码,再用R拼接成普通CSS样式:

primary_color <- theme_color_codes$primary

ui <- fluidPage(
  theme = my_theme,
  tags$style(paste0(".fa-li { color: ", primary_color, "; }")),
  # 你的UI内容
)

内容的提问来源于stack exchange,提问作者SimonSimon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 06:40:47