Explain Codes LogoExplain Codes Logo

Best way to use HTML5 data attributes with rails content_tag helper?

html
data-attributes
rails-content-tag-helper
html5
Alex KataevbyAlex Kataev·Jan 30, 2025
TLDR

Harness the power of the :data key with Rails helpers to stash HTML5 data- attributes. Use content_tag, spoon-feed a hash to :data, where hash keys carry the data attribute names. The tag helper serves a leaner syntax for single tags.

# Embedding 'data-' attributes in a div using `content_tag` <%= content_tag :div, "Don't touch me!", data: { toggle: "modal", target: "#modalId" } %> # Utilising `tag` for an input field <%= tag.input type: 'text', data: { placeholder: 'Make a wish...' } %>

Substitute "Don't touch me!", "modal", "#modalId", 'Make a wish...' with your needs. Check how these stanzas shape custom data attributes in a Rails view with minimum code.

Handling hyphenated attributes: Symbols can't be trusted

Suddenly facing hyphenated data attributes? It can be a hiccup using symbol notation, as Ruby symbols and hyphens are like cats and dogs. Here's the antidote:

<%= content_tag :div, "Example", :"data-attribute-with-hyphen" => "value" %> # OR swapping symbol with string <%= content_tag :div, "Example", data: { "attribute-with-hyphen" => "value" } %>

The first example relies on a symbol with quotes to outfox the hyphen hurdle, while the second elects a string key for compatibility.

Alloi's toolbox for dynamic data attributes

Dynamic data attributes can be infused into the mix using Rails helpers. The buffet includes:

  • Indulging variables for data:
    <%= content_tag :div, "Dynamic", data: { attribute: @your_variable_here } %>
  • Blending additional attributes like a master-chef:
    <%= content_tag :div, "Master Chef", alt: "@GordonRamsay", data: your_data_hash %>

Jiving jQuery with Rails

Mixing jQuery with Rails' data- attributes can be a blast for client-side antics. jQuery can read or swing data attributes, set by Rails:

$(document).ready(function() { $('.element').data('key'); // Fetches the data attribute like a dog fetching a frisbee $('.element').data('key', 'new value'); // Substitutes a new value like changing clothes });

Don't forget to clench the data attributes using the Rails helpers, so they can dance with jQuery.

Straight to the point with tag helper

Turning to the tag helper can lead to a champagne toast of readable and declarative code, especially when spinning a single tag with rich attributes:

<%= tag.div class: "user-card", data: { user_id: @user.id } do %> <%= tag.h3 @user.name %> <%= tag.p @user.bio %> <% end %>

This knack nests the class within the div, yielding a more organized and structured tactic for scribing views.