如何使用haml和rails进行数据属性?

我可以有

%a{href: '#', data_toggle_description_length: 'toggle_me_ajax'} 

它给了我强调的不是破折号,即

  

但是我想拥有HTML5 data-属性,即

  

但是当我尝试用破折号替换下划线时,即

 %a{href: '#', data-toggle-description-length: 'toggle_me_ajax'} 

我得到语法错误:

 /home/durrantm/Dropnot/webs/rails_apps/linker/app/views/links/_links.html.haml:13: syntax error, unexpected tLABEL ...data-toggle-description-length: 'toggle_me_ajax')}>\n tog... ... ^ /home/durrantm/Dropnot/webs/rails_apps/linker/app/views/links/_links.html.haml:13: syntax error, unexpected ')', expecting '}' ...ption-length: 'toggle_me_ajax')}>\n toggleMeAjax\n \... ... ^ /home/durrantm/Dropnot/webs/rails_apps/linker/app/views/links/_links.html.haml:13: unknown regexp options - pa /home/durrantm/Dropnot/webs/rails_apps/linker/app/views/links/_links.html.haml:13: syntax error, unexpected $undefined ... toggleMeAjax\n \n\n", -1, false);::Haml::Util.h... ... ^ /home/durrantm/Dropnot/webs/rails_apps/linker/app/views/links/_links.html.haml:13: unterminated string meets end of file /home/durrantm/Dropnot/webs/rails_apps/linker/app/views/links/_links.html.haml:13: syntax error, unexpected $end, expecting '}' 

试试这个:

 %a{"data-toggle-description-length" => "toggle_me_ajax", href: "#"} 

要么

 %a{href: "#", :data => {:toggle_description_length => "toggle_me_ajax"}} 

有关详细信息,请参阅此处

您也可以在线使用html2haml转换器

编辑:

正如评论中所提到的,还有更多的语法可以使用

  %a{href: "#", { "data-toggle-description-length": "toggle_me_ajax" }} 

要么

 %a{href: "#", { :"data-toggle-description-length" => "toggle_me_ajax" }} 

我仍然更喜欢前两个,因为我认为后者看起来很丑陋而且有点混乱。

在haml中真的不需要使用{ ... }样式。 HTML样式属性是一种更灵活,更自然的html生成方式。

 %a(href="#" data-toggle="target") my link 

不需要逗号,没有哈希火箭等。 您也可以非常轻松地插入或直接分配变量而无需切换样式。

例如

 %a(href=link data-toggle="#{id}-toggle") 

其中linkid是当前绑定范围的变量。

值得注意的是,你也可以无缝地包含来自xmlns的属性,svg生成使用了很多名称空间前缀,例如:

 %link(xlink:type="simple" xlink:href=link) 

使用其他风格没有令人信服的理由。