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

前端 未结 5 1899
予麋鹿
予麋鹿 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 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
    instead of , in your spacer template.

提交回复
热议问题