Working with data attributes use Rails tag helpers

How can I convert <div data-controller="slideshow" data-slideshow-index="1"> to the rails 5 tag heplers like <%= tag.div data: { controller: ''slideshow', ...} %> ?

<%= content_tag, :div, data: { controller: 'slideshow', slidesshow_index: 1 }%>

1 Like

You can also keep the data part with the identifier, if you want.

<%= content_tag :div, "data-controller": "slideshow", "data-slideshow-index": "1" >
1 Like

I find itā€™s much easier to keep things straight if I consistently use the quoted key format instead of the explicit data hash format. This is especially true when my controller names span to multiple words.

Because the controller name can appear as both a key prefix AND as a value, I want to be able to use the exact same sequence of characters when Iā€™m typing new code or searching existing code. However, because the explicit hash format requires me to underscore the keys instead of hyphenating them, I canā€™t do that - I have to keep track of both the underscore and the hyphen forms.

Luckily, the quoted key format keeps everything using hyphens.

Bad:

<%= content_tag(:div, data: {
  controller: 'multi-word-controller',                 # hyphens
  multi_word_controller_datumName: 'datumValue'        # underscores
}) do %>
  <%= content_tag(:div, 'act on me', data: {
    target: 'multi-word-controller.targetName'
  }) %>

  <%= content_tag(:div, 'click me', data: {
    action: 'multi_word_controller#actionName'
  }) %>
<% end %>

Here, Iā€™m consistently using the explicit data-hash format. But for my multi-word controller, I still have to search for both the hyphen (ā€˜multi-word-controllerā€™) and the underscore (ā€˜multi_word_controllerā€™) forms. As I create new DOM nodes, I also have to remember which separator character to use when.

Good:

<%= content_tag(:div,
  'data-controller': 'multi-word-controller',                  # hyphens
  'data-multi-word-controller-datumName': 'datumValue'         # hyphens
 ) do %>
  <%= content_tag(:div, 'act on me'
    'data-target': 'multi-word-controller.targetName'
  ) %>

  <%= content_tag(:div,'click on me'
    'data-action': 'multi-word-controller#actionName'
  ) %>
<% end %>

Here, Iā€™m consistently using the quoted-key format. The identifier ā€˜multi-word-controllerā€™ is now ALWAYS hyphen-delimited whether it occurs within a key or a value. I donā€™t have to think as I code my ERB, and I donā€™t have to use regular expressions when grepping.

There are a couple of side bonuses in the Ruby on Rails world:

  • Ruby names are underscore-delimited. If I have Ruby methods with similar names to my JavaScript objects, I know that when I search for the underscore form of an identifier, Iā€™ll find Ruby code. When I search for the hyphen form, Iā€™ll find JavaScript/DOM code.

  • TextMate theme does a better job of visually distinguishing the quoted keys than it does the explicit hash form.