gespinha
gespinha

Reputation: 8477

Ruby on rails raw tag inside a link_to

I have been having some problems with variables inside link_to tags, which only get to work when wrapped in a raw.

What does raw actually mean? Is it a good practice to use it to wrap strings and variables inside a tag?

Upvotes: 1

Views: 1215

Answers (3)

Nermin
Nermin

Reputation: 6100

Why you had problems, link_to helper accepts block as argument, you can insert any content inside link_to helper

For example:

<%= link_to 'link' do %>
  <p> First paragraph </p>
  <%= 'ruby string' %>
<% end %>

Will produce

<a href='/link'>
  <p> First paragraph </p>
  ruby string
</a>

Upvotes: 0

Simone Carletti
Simone Carletti

Reputation: 176352

From the official Rails raw documentation:

This method outputs without escaping a string. Since escaping tags is now default, this can be used when you don't want Rails to automatically escape tags. This is not recommended if the data is coming from the user's input.

It's not a good practice to use raw because it bypasses the default Rails input sanitization. Use it only if you know what you are doing.

If you need to use raw HTML inside the link to, you can also pass it as a block.

<%= link_to root_url do %>
  <span>My link</span>
<% end %>

Another alternative is to use the Rails helpers which sanitizes the input.

<%= link_to content_tag(:span, "Unsafe input"), root_url %>

Upvotes: 1

Joel
Joel

Reputation: 4593

raw outputs without escaping the string

raw docs

Upvotes: 0

Related Questions