link_to image_tag with inner text or html in rails

后端 未结 9 1547
生来不讨喜
生来不讨喜 2020-12-02 16:59

I want to output the following with Ruby on Rails link_to and image_tag methods:

Lorem Ipsum 

        
相关标签:
9条回答
  • 2020-12-02 17:21

    Or a shorter way is

    <%= link_to image_tag('image/someimage.png') + "Some text", some_path %>
    
    0 讨论(0)
  • 2020-12-02 17:23

    I prefer this approach in HAML

    = link_to root_path do
      = image_tag "ic_launcher.png", size: "16x16"
      Home
    
    0 讨论(0)
  • 2020-12-02 17:29

    Why not just use a link to and image tag?

    <%= link_to "hiii #{image_tag(yourimagepath)}", "link_path" %>
    

    You could also try the appending done above (string + image_tag), but it will throw an error if one of those things becomes nil. Using interpolation, it will just show a blank image(or string) if it is nil.

    For Rails 3, you will need to use html_safe:

    <%= link_to "hiii #{image_tag(yourimagepath)}".html_safe, "link_path" %>
    
    0 讨论(0)
  • 2020-12-02 17:30

    Here's a cool way to use a link_to to include an image, and a mailto href with Text (displayed next to the image):

    <%= link_to image_tag("image.png") + " some@email.com", 
                             href: "mailto:some@email.com" %>
    

    Giving you something like this in your view (the entire image and text become an mailto href):

    hyperlinked image and text with mailto

    0 讨论(0)
  • 2020-12-02 17:32

    You can use blocks as an alternative to the string interpolation with correct usage html_safe. For example:

    <%= link_to '#' do %>
      Lorem Ipsum <%= image_tag('/images/menu-arrow-down.gif') %>
    <% end %>
    
    0 讨论(0)
  • 2020-12-02 17:33
    link_to(image_tag("image.png", :alt =>  "alt text", :class =>"anyclass"), image_url) 
    
    0 讨论(0)
提交回复
热议问题