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.
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):
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With