Can I make an array of links using link_to in Rails?

前端 未结 5 1920
予麋鹿
予麋鹿 2021-02-19 13:29

I have a list of values in url/title pairs that I\'d like to display. (More specifically, each object has its own list of links, some with 0, some with 1, some with more.) I w

相关标签:
5条回答
  • 2021-02-19 13:56

    Use safe_join combined with html_safe on the separator string.

    Example:

    <%= safe_join(links.map { |l| link_to(l.title, l.url) }, ", ".html_safe) %>
    
    0 讨论(0)
  • 2021-02-19 14:13

    Rails will convert strings to be html safe by default. Your join call turns the links output into a string, which is why the text is then being escaped. Try adding .html_safe after the join call, which will tell rails that the text you are providing is html safe and so does not need to be escaped. There's more on how this works at: http://yehudakatz.com/2010/02/01/safebuffers-and-rails-3-0/

    0 讨论(0)
  • 2021-02-19 14:16

    While the suggestions to use html_safe will get the result you are going for, I would suggest you not stick loops like that in your view. There is a perfectly good way in rails to do what you are looking for:

    In your main view file where you currently have your loop change it to this:

    <%= render partial: 'links/link', collection: links, spacer_template: 'shared/comma' %>
    

    Then create a partial links/_link.html.erb

    <%= link_to link.title, link.url %>
    

    Then create a partial shared/_comma.html.erb

    ,
    

    The nice thing about this approach is you don't have to worry if your link content is actually safe and if you choose to list or style it another way it's as simple as changing one or both of the templates. For example if instead of commas you decide you want it vertical and use <br> instead of , in your spacer template.

    0 讨论(0)
  • 2021-02-19 14:16

    Try

    <%= links.map{|wl| link_to wl.title, wl.url}.join(', ').html_safe %>
    

    This instructs Rails to not escape the text.

    0 讨论(0)
  • 2021-02-19 14:18

    Try putting this in your ApplicationHelper

      def sep(separator)
        ->(a, b){ a << separator.html_safe << b }
      end
    

    Then do this in your template

    links.map{|wl| link_to wl.title, wl.url}.reduce(&sep(", "))
    

    You can use any separator you like this way. You also don't need to call html_safe on the whole thing either. Only the separator. So this method is more secure.

    0 讨论(0)
提交回复
热议问题