Ruby-on-rails 在 Slim 中处理数据属性的最佳方式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18948017/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best way to handle data attributes in Slim
提问by mmoss
I was evaluating Slimas a replacement for HAMLin a personal project, and it doesn't appear to handle HTML5 data attributes as gracefully as HAML. I was hoping someone may have also run into this, or may have known about an option/syntax I haven't yet found in their docs.
我在个人项目中评估Slim作为HAML的替代品,它似乎不像 HAML 那样优雅地处理 HTML5 数据属性。我希望有人可能也遇到过这个问题,或者可能知道我在他们的文档中还没有找到的选项/语法。
HAML allows you to define HTML 5 data attributessimply by using nested hashes like so:
HAML 允许您简单地使用嵌套散列来定义HTML 5 数据属性,如下所示:
%a{data: {key1: 'val', key2: 'val'}}
%a{data: {key1: 'val', key2: 'val'}}
resulting in
导致
<a data-key1='val' data-key2='val'></a>
<a data-key1='val' data-key2='val'></a>
回答by Billy Chan
There are multiple ways in Slim
Slim有多种方式
As Hash
Attributes which will be hyphenated if a Hash is given (e.g. data={a:1,b:2} will render as data-a="1" data-b="2")
Use it directly as "mu is too short" mentioned, quite intuitive.
a data-title="help" data-content="foo"Use Ruby code. I often do this and rarely above.
= link_to 'foo', bar_path, data: {a: 'a', b: 'b'}
作为哈希
如果给定哈希值,属性将被连字符(例如 data={a:1,b:2} 将呈现为 data-a="1" data-b="2")
直接用,就像前面提到的“mu 太短”一样,很直观。
a data-title="help" data-content="foo"使用 Ruby 代码。我经常这样做,很少在上面。
= link_to 'foo', bar_path, data: {a: 'a', b: 'b'}
回答by The Whiz of Oz
Use the splatoperator:
使用splat运算符:
h1#section-title*{'data-url'=>'test', 'data-id'=>'test'} = @project.name
回答by Slawomir Wdowka
.your-class*{data: {first_attribute: 'first value', second_attribute: 'second value'} }
Will produce
会产生
<div class="your-class" data-first_attribute="first value" data-second_attribute="second value"></div>
回答by Juan José
I prefer this kind to fix...
我更喜欢这种修复...
@products.each do |product|
.module data-id=product.id
It is working for me
它对我有用

