Mayer
Mayer

Reputation: 23

How to rewrite HTML for Rails

I'm trying to re-write the code below so that it will use an image_tag. I know how to apply a class attribute, but how do I apply a custom attribute like "data-dark-logo"?

I'm learning how to develop and am building an application that has the following HTML:

<div id="logo">
  <a href="index.html" class="standard-logo" data-dark-logo="external_assets/images/logo-dark.png">
    <img src="external_assets/images/logo.png" alt="Canvas Logo">
  </a>
  <a href="index.html" class="retina-logo" data-dark-logo="external_assets/images/[email protected]">
    <img src="external_assets/images/[email protected]" alt="Canvas Logo">
  </a>
</div>

I'm trying to rewrite this so it will function in my Rails app.

Upvotes: 0

Views: 226

Answers (3)

Mayer
Mayer

Reputation: 23

The solution I came up with looks like this:

    <div id="logo">
    <%= link_to welcome_index_path, class: 'standard-logo', data: {'dark-logo' => asset_path("front/logo-dark.png") } do %>
        <%= image_tag("front/logo.png") %>
    <% end %>
    <%= link_to welcome_index_path, class: 'retina-logo', data: {'dark-logo' => asset_path("front/[email protected]") } do %>
        <%= image_tag("front/[email protected]") %>
    <% end %>
    </div>

But I'm not sure if this complies with Rails best practices

Upvotes: 0

Aaron
Aaron

Reputation: 228

Like this?

<div id="logo">
    <%= link_to("index.html", class: "standard-logo", data-dark-logo: "external_assets/images/logo-dark.png") do %>
        <%= image_tag("external_assets/images/logo.png",    alt: "Canvas Logo") %>
    <% end %>
    <%= link_to("index.html", class: "retina-logo",   data-dark-logo: "external_assets/images/[email protected]") do %>
        <%= image_tag("external_assets/images/[email protected]", alt: "Canvas Logo") %>
    <% end %>
</div>

Edit:

To make the data-dark-logo pull your asset from the asset pipeline, try using the asset_path helper:

<%= link_to("index.html", class: "standard-logo", data-dark-logo: asset_path("external_assets/images/logo-dark.png")) do %>

Upvotes: 1

coderhs
coderhs

Reputation: 4827

Just pass the data attributes as a hash.

<%= link_to '/link', class: 'standard-logo', data: {'dark-logo' => 'external_assets/....' do %>
  <%= image_tag ('external_assets/...') %>
<% end %>

Upvotes: 1

Related Questions