如何在Typst中正确获取state的强类型底层值?
解决Polylux中State类型不匹配导致主题颜色无法获取的问题
问题核心在于:Polylux的state对象存储的是content类型数据,而你用AllThemes.at()访问record时需要的是字符串类型的键,直接使用state.display()或直接引用state对象会导致类型不匹配报错。
修正方案
用str()函数将state的内容转换成字符串,即可将其作为合法键访问record中的主题配置。
修正后的完整代码示例
#let RedTheme = (light: rgb(255, 0, 0), dark: rgb(128, 0, 0)) #let GreenTheme = (light: rgb(0, 255, 0), dark: rgb(0, 128, 0)) #let AllThemes = (theme1: RedTheme, theme2: GreenTheme) #let theme = state("theme", "theme1") #let template(user-theme: "", body) = { // 处理空主题参数,兜底用默认值 let selected-theme = user-theme != "" ? user-theme : "theme1" theme.update(selected-theme) body } #show: template.with(user-theme: "theme2") // 用str()转换state内容为字符串,解决类型问题 #let current-theme = AllThemes.at(str(theme)) // 正常访问主题颜色 #current-theme.light
额外注意事项
- 给
template的user-theme参数增加空值兜底逻辑,避免传入空字符串时state被设置为空,导致后续主题获取失败。 - 若直接通过
state("theme")获取状态,同样用str(state("theme"))转换即可,效果与str(theme)一致。
内容的提问来源于stack exchange,提问作者lukasbm
相关产品推荐
相关产品推荐

