元内容在MVC中位于何处? [英] Where does the meta content live in the MVC?

查看:96
本文介绍了元内容在MVC中位于何处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在考虑MVC中的元内容,特别是页面标题和元描述(这对于指导Google在搜索结果中显示的片段非常有用).

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

尽管如此,我仍无法就此决定住哪里. (对于UGC应用程序而言),通常存在一些逻辑,这取决于读者如何与内容进行交互.

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.

推荐答案

通常使用帮助器content_foryield设置元内容.

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

例如:

# 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
%>

如果您打算进行流式传输,则应改用provide您的助手中的content_for.

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

永远不要在用于元内容(例如@title = 'blabla'; @description = 'blablabla')的控制器中放置实例变量

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)

这篇关于元内容在MVC中位于何处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆