Adding Data Attributes using haml_tag

A guide to using haml_tag to add data attributes - dealing with hyphens

Normally when using haml_tag you can add attributes by typing something like; haml_tag :a, class: 'my-class'

Unfortunately because of the hyphen in data attributes the same pattern doesn’t work if you try and add them, so haml_tag :a, data-id: '5' will crap itself.

What you can do though is call something like; haml_tag :a, data: {id: '5'} which will output the following HTML; <a data-id='5'></a>

You can also add multiple data attributes like so; haml_tag :a, data: {id: '5', type: 'arbitrary code'} which is pretty handy.


Recent posts View all

Ruby

Forcing a Rails database column to be not null

How you can force a table column to always have something in it with Rails

Writing Marketing

We've deleted an article's worth of unhelpful words

We've improved several pages across our site by removing words that add no value, and often detract from the article.