61

I was evaluating Slim as a replacement for HAML in 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.

HAML allows you to define HTML 5 data attributes simply by using nested hashes like so:

%a{data: {key1: 'val', key2: 'val'}}

resulting in

<a data-key1='val' data-key2='val'></a>

mmoss
  • 713
  • 1
  • 5
  • 5

4 Answers4

97

There are multiple ways in Slim

  1. 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")

  2. Use it directly as "mu is too short" mentioned, quite intuitive.

    a data-title="help" data-content="foo"
    
  3. Use Ruby code. I often do this and rarely above.

    = link_to 'foo', bar_path, data: {a: 'a', b: 'b'}
    
Billy Chan
  • 24,625
  • 4
  • 52
  • 68
  • Awesome, **#3** is exactly what I was looking for. I didn't see anything jump out at the docs describing this the way the HAML docs did. Thanks! – mmoss Sep 22 '13 at 20:31
  • 3
    moss, #3 is neither Haml nor Slim but Rails helper :) – Billy Chan Sep 23 '13 at 02:15
  • 3
    Note if you do `a href="#" data={user_name: 'fred', user_id: 1}` it will translate this to `` - this is nothing to do with Rails as you'll see it working in Sinatra apps as well. – Dave Sag Jan 21 '14 at 05:59
  • 2
    Note that #3 doesn't work for direct div elements like `.container, data: { url: "link", value: "stuff" }` Instead you have to use #2, like `.container[ data-url="link data-value="stuff" ]` – ahnbizcad Sep 29 '14 at 05:04
  • 1
    Just to mention it: Slim is truly beautiful. – Alexander Presber Jun 25 '15 at 07:57
  • in case you want to separate to multiple lines use: div(data-a="asdf" data-b="qwer") – flaudre Sep 07 '16 at 09:22
  • Underscores in a key are not replaced by hyphens since Slim 4.0 (e.g. `data: {user_id: 1}` is converted to `data-user_id="1"`) – uasi Sep 03 '18 at 07:33
3

Use the splat operator:

h1#section-title*{'data-url'=>'test', 'data-id'=>'test'} = @project.name
The Whiz of Oz
  • 6,763
  • 9
  • 48
  • 85
3
.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>
Slawomir Wdowka
  • 540
  • 2
  • 6
0

I prefer this kind to fix...

@products.each do |product|
  .module data-id=product.id

It is working for me

Juan José
  • 39
  • 5