Best way to handle data attributes in Slim

Ruby on-RailsRubyHamlTemplatingSlim Lang

Ruby on-Rails Problem Overview


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>

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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'}
    

Solution 2 - Ruby on-Rails

Use the splat operator:

h1#section-title*{'data-url'=>'test', 'data-id'=>'test'} = @project.name

Solution 3 - Ruby on-Rails

.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>

Solution 4 - Ruby on-Rails

I prefer this kind to fix...

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

It is working for me

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmmossView Question on Stackoverflow
Solution 1 - Ruby on-RailsBilly ChanView Answer on Stackoverflow
Solution 2 - Ruby on-RailsThe Whiz of OzView Answer on Stackoverflow
Solution 3 - Ruby on-RailsSlawomir WdowkaView Answer on Stackoverflow
Solution 4 - Ruby on-RailsJuan JoséView Answer on Stackoverflow