Where does the meta content live in the MVC?

前端 未结 1 1688
日久生厌
日久生厌 2021-02-06 11:14

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).

相关标签:
1条回答
  • 2021-02-06 11:45

    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)
    0 讨论(0)
提交回复
热议问题