Using link_to with embedded HTML - ruby-on-rails

I'm using Twitter's Bootstrap stuff and I have the following HTML:
<a class="btn" href="<%= user_path(#user) %>"><i class="icon-ok icon-white"></i> Do it#</a>
What's the best way to do this in Rails? I'd like to use <%= link_to 'Do it', user_path(#user) %> but the <i class="icon-ok icon-white"></i> is throwing me off?

Two ways. Either:
<%= link_to user_path(#user) do %>
<i class="icon-ok icon-white"></i> Do it#
<% end %>
Or:
<%= link_to '<i class="icon-ok icon-white"></i> Do it#'.html_safe, user_path(#user) %>

I had the same need recently. Try this:
<%= link_to '<i class="icon-ok icon-white"></i> Do it'.html_safe, user_path(#user) %>

You have also the possibility to create an helper method like below:
def link_fa_to(icon_name, text, link)
link_to content_tag(:i, text, :class => "fa fa-#{icon_name}"), link
end
Adapt the classes to your needs.

In normal HTML we do,
<i class="fa fa-user-plus"></i> Register
In Ruby On Rails:
<%= link_to routeName_path do %>
<i class="fa fa-user-plus"></i> Link Name
<% end %>
<%= link_to register_path do %>
<i class="fa fa-user-plus"></i> Register
<% end %>

If you want a link in rails that uses that same icon class from twitter bootstrap all you need to do is something like this.
<%= link_to "Do it#", user_path(#user), :class => "btn icon-ok icon-white" %>

Using HAML:
= link_to model_path do
%img{src: '/assets/someimg.png'}

In the gem twitter-bootstrap-rail : they create a helper glyph
def glyph(*names)
content_tag :i, nil, :class => names.map{|name| "icon-#{name.to_s.gsub('_','-')}" }
end
So you can use it like: glyph(:twitter)
and you link helper could look like: link_to glyph(:twitter), user_path(#user)

I will give this a shot since you haven't accepted an answer yet
and the other answers are not 100% what you were looking for.
This is the way to do it the Rails way.
<%= link_to(user_path(#user), :class => 'btn') do %>
<i class="icon-ok icon-white"> </i> Do it!
<% end %>
Edit: leaving my answer for future reference,
but #justin-herrick has the correct answer when
working with Twitter Bootstrap.

I think you can simplified it through a helper method if you use it frequently in your application.
put it in helper/application_helper.rb
def show_link(link_text, link_source)
link_to("#{content_tag :i, nil, class: 'icon-ok icon-white'} #{link_text}".html_safe,
link_source, class: "btn")
end
Then call it from your view file just like link_to
<%= show_link "Do it", user_path(#user) %>

If you are using the bootstrap 3.2.0, you can use this helper in your app/helpers/application_helper.rb
module ApplicationHelper
def glyph(*names)
content_tag :i, nil, :class => names.map{|name| "glyphicon glyphicon-#{name.to_s.gsub('_','-')}" }
end
end
and then, in your views:
link_to glyph(:pencil) + ' Edit', edit_post_path(#post), class: 'btn btn-warning'

def show_link (source, text)
link_to source, {'data-original-title' => 'Show', 'data-toggle' => 'tooltip', :class => 'btn btn-xs btn-success'} do
"#{text} #{content_tag :i, nil, class:' glyphicon glyphicon-eye-open' }".html_safe
end
end

Helper based on Titas Milan's suggestion, but using a block:
def show_link(link_text, link_source)
link_to link_source, { class: 'btn' } do
"#{content_tag :i, nil, class: 'icon-ok icon-white'} #{link_text}".html_safe
end
end

Related

Build external url in Rails that look nice

i am rendering an external link with this view:
<%= link_to public_web(company), class:" text-sm text-decoration-none", :target => "_blank" do %>
<i class="fa fa-globe mr-3"></i>
<span class="text-muted"><%= "#{public_web(company)}" %></span>
<% end %>
and the following helper
def public_web(company)
URI::HTTPS.build({:host => company.marketings.first.try(:website)}).to_s
end
However the url length breaks the UI design (I would like to control the maximum length)
How can I truncate it ?
Solution :
I modified the helper as follows:
def public_web(company)
response = URI::HTTPS.build({:host => company.marketings.first.try(:website)}).to_s
truncate(response, length: 25, omission: '...')
end
If you're just looking to truncate the text of the link then this is one way
<%= link_to public_web(company).truncate(20), class:" text-sm text-decoration-none", :target => "_blank" do %>
<i class="fa fa-globe mr-3"></i>
<span class="text-muted"><%= public_web(company) %></span>
<% end %>
Read more on the truncate method in Rails

add erb tag to link_to class in rails

I have a link class like
link_to( class: 'btn_download<%= index %>')
from a .each_with_index model call
Model.each_with_index do |m, index|
but it throws an error
and when i try with #{index} it just adds #{index} to the class name instead of dynamically adding 'index'
As I noticed there are some issues in your code. Please find below the code snippet example I wrote similar to your case which will help you to fix your issue
<% User.all.each_with_index do |m, index| %>
<%= link_to users_path, class: "btn_download#{index}" do %>
<span class="fa fa-sign-out"></span>
Download
<% end %>
<% end %>
So instead of using 'btn_download <%= index %>' try "btn_download#{index}".
Also, Use double quotes
class: "btn btn-primary btn-sm download_btn#{index}"
instead
class: 'btn btn-primary btn-sm download_btn#{index}'
Please let me know if you have any confusion in this.
If you want to wrap your link around an icon, use the following syntax:
<%= link_to ..._path(...) do %>
<i class="fa fa-spin fa spinner"></i>
<% end %>
You have to append a do onto the link to and then close the block with an end. And just put whatever inbetween (icon or image or div).

What's the best to include HTML tags before text produced by link_to?

basically I want the following output with link_to:
<i class="some-class"></i>Some text
Any suggestions?
<%= link_to "#" do %>
<i class="some-class"></i>Some text
<% end %>
Block form of link_to for the win!
What about content_tag ?
link_to "#{content_tag(:i, "", :class => 'some-class')}Some text".html_safe, root_url

Adding a Twitter Bootstrap button icon to button_to in Rails

I am working through the Agile Web Development with Rails book but I have been using Twitter Bootstrap instead of the custom styling from the book. I am having trouble adding an icon through GLyphonics to the button_to method. My code looks like this:
<%= button_to <i class="icon-search icon-white">Add To Cart</i>,
line_items_path(product_id: product),
class: "btn btn-success" %>
I have tried quite a few variations but can't seem to get it to work correctly.
I'm not sure how the OP got this to work, but Rails button_to generates an <input type='submit' /> element, which does not allow for HTML in the value field.
See also: input type="submit" Vs button tag are they interchangeable?
The best alternative in this situation is to force link_to to PUT (or POST):
<%= link_to raw("<i class=\"icon-search icon-white\">Add To Cart</i>"),
line_items_path(product_id: product),
class: "btn btn-success",
method: :put %>
You can add the icon as a child element:
<%= button_to button_path, method: :delete do %>
<span class="glyphicon glyphicon-search"></span>
<% end %>
It looks like you have an issue with your quotes:
<%= button_to raw("<i class=\"icon-search icon-white\">Add To Cart</i>"),
line_items_path(product_id: product),
class: "btn btn-success" %>
Enclose the label of the button in double quotes, escape the double quotes in your i tag, and finally, wrap everything into a raw() call to ensure the HTML is properly displayed.
Alternatively you can use html_safe:
<%= button_to "<i class=\"icon-search icon-white\">Add To Cart</i>".html_safe,
line_items_path(product_id: product),
class: "btn btn-success" %>
good point from #jordanpg: you can't have HTML in the value of a button, so his solution is more appropriate and should get the approved status.
the html_safepart remains valid though.
Using raw() or #html_safe still did not work for me.
I am using a helper method to create a button_to flag content. Ended up using the following in my helper method (path is defined beforehand):
form_tag path, :method => :post do
button_tag do
content_tag :i, 'Flag as inappropriate', :class => 'icon-flag flag_content'
end
end
I used this one and it works fine for me :
<%= link_to(line_items_path(product_id: product),
method: :put,
class: 'btn btn-success') do %>
<%= content_tag('i', nil, class: 'icon-search icon-white') %> Add To Cart
<% end %>
Hope this helps
I am using this helper:
module ApplicationHelper
def glyph(*names)
content_tag :i, nil, class: names.map{|name| "icon-#{name.to_s.gsub('_','-')}" }
end
end
Example:
glyph(:share_alt)
=> <i class="icon-share-alt"></i>
and
glyph(:lock, :white)
=> <i class="icon-lock icon-white"></i>
Using Rails 4 and Bootstrap 3, here's how to create a delete button using link_to or button_to.
Note that I'm using Haml instead of Erb.
In your view:
- #users.each do |user|
= link_to content_tag(:i, ' Delete', class: "glyphicon glyphicon-trash"),
users_path(user),
class: "btn btn-danger",
method: :delete,
data: { confirm: "Delete user #{user.username}?" }
You can also replace the content_tag part with
raw('<i class="glyphicon glyphicon-trash"> Delete</i>'),
This work for me, (and with confirm message)
<%= button_to "/home/delete?cardId="+card.id.to_s, data: { confirm:'Are you sure you want to delete?' } do %>
<i class="fa fa-times"></i>
<% end%>
this generate
<form class="button_to" method="post" action="/home/delete?cardId=15">
<button data-confirm="Are you sure you want to delete?" type="submit">
<i class="fa fa-times"></i>
</button>
</form>

How do I add a span in a link_to with an image

So I have this:
<%= link_to(image_tag(#model.picture.url(:thumb), :alt => ''), "/pages/you/#{something.id}", {:id => "y_link_#{something.id}"}) %>
Which works, but I need a span in between also like this:
<a id="y_link_2" href="/pages/you/2" class="">
<span>Apples</span>
<img src="another_small.jpg?1236340989" alt="">
</a>
How do I add
<span>Apples</span>
to the link_to?
Feed a block to your link_to call:
<% link_to("/pages/you/#{something.id}", {:id => "y_link_#{something.id}"}) do %>
<%= content_tag(:span, 'Apples') %>
<%= image_tag(#model.picture.url(:thumb), :alt => '') %>
<% end %>
Alternatively:
<% link_to("/pages/you/#{something.id}", {:id => "y_link_#{something.id}"}) do %>
<span>Apples</span>
<%= image_tag(#model.picture.url(:thumb), :alt => '') %>
<% end %>
image_tag and content_tag return basic strings, so they can be concatenated using the + operator easily:
<%= link_to(content_tag(:span, "Apples") + image_tag(#model.picture.url(:thumb), :alt => ''), "/pages/you/#{something.id}", {:id => "y_link_#{something.id}"}) %>
However, as you can see, it gets quite messy - might be worth moving it into a helper method.
For a path, use the structure like so
<%= link_to edit_section_path(#section) do %>
Edit
<span class="fa fa-list pull-right"></span>
<% end %>
Haml lends itself well to situations like these. For example:
= link_to "/pages/you/#{something.id}", id: "y_link_#{something.id} do
%span Apples
= image_tag(#model.picture.url(:thumb), alt: '')
Alternatively:
%a[something, 'y_link']{href: "/pages/you/#{something.id}"}
%span Apples
%img{src: #model.picture.url(:thumb)}
It's worth learning if you want to write your views faster and read them better.

Resources