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

使用templ设置HTML li元素style属性时遭遇解析错误求助

问题解决:templ中动态设置style属性报错的原因与修复方案

报错原因

templ对style属性的解析逻辑和class存在差异:

  • class属性支持直接传入字符串或templ.Class类型,解析器可正常识别;
  • style属性默认要求传入templ.Style类型,直接传递普通字符串会触发解析器的节点校验错误,也就是你遇到的“parsing error: for: expected nodes, but none were found”。

修复方案

方案1:使用templ.Attribute显式设置style属性

通过templ.Attribute手动构造属性,绕过解析器对style的特殊校验:

<ol>
  for _, e := range events {
    <li class={ e.Class } { templ.Attribute("style", e.Style) }>
      <a>
        <p>{ e.Title }</p>
      </a>
    </li>
  }
</ol>

方案2:将style值转为templ.Style类型

在Go代码中把Event结构体的Style字段类型改为templ.Style,构造对象时传入格式化后的样式字符串:

import "github.com/a-h/templ"

type Event struct {
  Class string
  Style templ.Style
  Title string
}

// 构造事件对象示例
event := Event{
  Class: "event-item",
  Style: templ.Style("gridRow: 3 / span 4"),
  Title: "研讨会",
}

修改后模板中直接使用style={ e.Style }即可正常渲染。

补充说明

你提到的用CSS类替代的方案确实可行,但在动态style的场景下,以上两种方法能更直接满足需求。templ对style的严格校验是为了确保样式的安全性和渲染正确性,避免非法CSS注入或格式错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 15:52:12