Best way to handle data attributes in Slim
Asked Answered
S

4

62

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>

Selfregulated answered 22/9, 2013 at 19:42 Comment(0)
G
99

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'}
    
Gangboard answered 22/9, 2013 at 20:9 Comment(7)
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!Selfregulated
moss, #3 is neither Haml nor Slim but Rails helper :)Gangboard
Note if you do a href="#" data={user_name: 'fred', user_id: 1} it will translate this to <a href="#" data-user-name="fred" data-user-id="1"></a> - this is nothing to do with Rails as you'll see it working in Sinatra apps as well.Spermiogenesis
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" ]Bello
Just to mention it: Slim is truly beautiful.Testosterone
in case you want to separate to multiple lines use: div(data-a="asdf" <you can insert a line break here>data-b="qwer")Sable
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")Fidler
T
3

Use the splat operator:

h1#section-title*{'data-url'=>'test', 'data-id'=>'test'} = @project.name
Thithia answered 17/7, 2017 at 10:19 Comment(0)
B
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>
Broadloom answered 29/8, 2019 at 10:5 Comment(0)
D
0

I prefer this kind to fix...

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

It is working for me

Desist answered 20/6, 2016 at 6:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.