link_to image_tag with inner text or html in rails

后端 未结 9 1573
生来不讨喜
生来不讨喜 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:44

    I cannot seem to figure out how to add a comment to @corroded's answer. However, if you are using Rails 3, his answer will not work as expected. It might not be immediately obvious how to fix this, at least it wasn't for me. I knew I needed to add html_safe, but put it in the wrong place. In retrospect, it was obvious, but I thought I would include it here for others like me who make the "rookie" mistake.

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

    be careful though, if you are using a user assignable variable for "hiii" you need to sanitize it first.

    <%= link_to (h(my_model.some_string) + image_tag(yourimagepath)).html_safe,
                "link_path" %>
    

    Note that there is no issue with my_model.some_string or yourimagepath being nil because both h() and image_tag() return strings when passed nil.

提交回复
热议问题