Where does the meta content live in the MVC?

2020-05-28 10:26发布

问题:

I've been thinking about meta content in MVC, specifically the page title and the meta description (which is useful for guiding the snippet Google shows on your search result).

I can't come to a firm decision about where this should live though. There's often a little bit of logic around it depending (for a UGC application) on how readers have interacted with the content.

I can't decide whether this meta content is better constructed in the view layer or the controller. It almost certainly doesn't live in the model since it is specific to a particular view of the data however while my first instinct was to put it in the view I feel that it might be better abstracted.

I'm interested in what approach other people have taken.

回答1:

Meta content is typically set using helpers, content_for and yield.

For instance:

# app/helpers/application_helper.rb
def title(title)
  content_for :title, title
end

def description(description)
  content_for :description, description
end

# app/views/layouts/application.html.erb
<title>My app <%= yield :title %></title>
<meta name="description"><%= yield :description %></meta>

# app/views/some_controller/some_action.html.erb
<%
title @an_instance.an_attribute # or whatever you want by the way
description @an_instance.another_attribute
%>

If you intend to do streaming, you should use provide instead of content_for in your helpers.

Never ever put an instance variable in your controller that is used for meta content (such as @title = 'blabla'; @description = 'blablabla')

Here are some resources that do the same (list non-exhaustive):

  • BUILDING BULLETPROOF VIEWS (the slides are downloadable)
  • Rails Best Practices (commercial)