Can I use link_to to link an image and a text

2019-02-07 03:06发布

Well, I am using "font-awesome-rails" gem. I am pretty much used to font-awesome outside Rails, but I guess it's not that popular among Rails community.

Once installed, it creates icons using the format

<i class="nameoftheicon"> </i>

I thought of using it for my site logo, which would consist of the icon from font-awesome and some text. So I tried:

<%= link_to "", root_path, class: "icon-puzzle-piece icon-2x" %>
<%=  link_to "My site", root_path, id: 'logo'  %>

It works, but when I hover, they act as two different elements.

  1. What is the Rails way of combining an image and a text under a single <a> tag.

  2. And is there any popular Rails alternative to font-awesome?

5条回答
霸刀☆藐视天下
2楼-- · 2019-02-07 03:29

Try it,

You can directly mention rails image_tag in link_to as,

<%= link_to image_tag("image_name")+"your text", root_path, :class=>"icon-puzzle-piece icon-2x" %>
查看更多
Ridiculous、
3楼-- · 2019-02-07 03:33

Pass a block to link_to and the block will be linked

<%= link_to path, id: "logo" do %>
  <i class="icon-puzzle-piece icon-2x"></i>
  My Super Site
<% end %>
查看更多
时光不老,我们不散
4楼-- · 2019-02-07 03:35

Yes, you are using a vector font as image but you can use image_tag too, for example:

<%= link_to user_root_path, :class=> "user" do
      image_tag("image.jpg", :alt => current_user.name) +
      t("dashboard.my_account")
    end %>

Don't forget link together both of them with "+"

查看更多
我命由我不由天
5楼-- · 2019-02-07 03:36

Yes you can. For complex anchor such as images, just remove the first argument(the link text or anchor), and attach a block after the method.

link_to(root_path){<i class="icon"></i>}

The content inside block will become the anchor.

查看更多
We Are One
6楼-- · 2019-02-07 03:51

Hey guys this is a good way of link w/ image (it has lot of props in case you want to css attribute for example replace "alt" or "title" etc)

<%= link_to image_tag("#{request.ssl? ? @image_domain_secure : @image_domain}/images/linkImage.png", {:alt=>"Alt title", :title=>"Link title"}) , "http://www.site.com"%>

Hope this helps!

查看更多
登录 后发表回答