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

Rails中如何将HTML的data属性正确转换为HAML格式?

嘿,我来帮你搞定这个HAML的写法问题!

你遇到的问题主要是两个小细节没处理对:

  1. 类名的匹配:你的目标class是search-wrapper(连字符),但你写的是.search_wrapper(下划线),这会导致生成的HTML类名和预期不符,得先把类名改成.search-wrapper。

  2. data属性的HAML语法限制:Ruby的符号不允许包含连字符,所以你用:data-slideout-ignore作为哈希键是不合法的。这里给你几种正确的写法:

写法一:直接写HTML风格的data属性(最直观)

.search-wrapper data-slideout-ignore=true

写法二:用字符串作为哈希键

.search-wrapper {"data-slideout-ignore" => true}

写法三:用下划线代替连字符的符号(HAML自动转连字符)

HAML会自动把下划线命名的data属性转换成连字符格式,所以可以这样写:

.search-wrapper {:data_slideout_ignore => true}

或者更简洁的省略大括号写法:

.search-wrapper data_slideout_ignore=true

以上几种写法都会生成你需要的HTML:

<div class="search-wrapper" data-slideout-ignore="true"></div>

如果只需要属性存在、不需要赋值(比如<div class="search-wrapper" data-slideout-ignore></div>),可以简化成:

.search-wrapper data-slideout-ignore

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:09:27