ben
ben

Reputation: 29777

Where to put repeating display code for views in a Ruby on Rails app?

I have a Note model, which can contain have either an image link attachment (linktype = "image" or some text (linktype = "text). When I display the notes, the method of display changes depending on the linktype. An example is:

<% @notes.each do |q| %>
    <h2 class="title"><%= q.name %></h2>
    <% if q.linktype == "image"%>
        <img src="<%= q.link %>" />
    <% elsif q.linktype == "text"%>
        <%= q.text %>
    <% end %>
<% emd %>

I have to display the notes in a few different views in my site, so rather than have to repeat the viewing code multiple times, I want to have it in one place and refer to it from different views.

Should I do this in the application helper? If so, do I put the display code, like the code above, directly into the helper, or is there a better way? Thanks for reading.

Upvotes: 1

Views: 327

Answers (1)

clyfe
clyfe

Reputation: 23770

For repeating view code that has nothing to do with some entity (is not, say, users/show.html.erb) make a widgets folder and write your partial there. I put in my widgets nav-bars and such.

/app/views/widgets/widget1.html.erb
/app/views/widgets/widget2.html.erb
...

# some_view.html.erb
<%= render :partial => 'widgets/widget1' %>

In an abstract way, I make the difference between helpers and this kind of partials as so:

  • helpers are for view-related logic (iterate in a special way etc)
  • view widgets are data image, they just match holes with data

Upvotes: 5

Related Questions