Rails页面标题 [英] rails page titles

查看:82
本文介绍了Rails页面标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不喜欢rails缺省页面标题的方式(只是使用控制器名称),所以我正在开发一种新的方式来实现它:

I don't like the way rails does page titles by default (just uses the controller name), so I'm working on a new way of doing it like so:

应用程序控制器:

application controller:

def page_title
    "Default Title Here"
end

帖子管理员:

def page_title
    "Awesome Posts"
end

应用程序布局:

<title><%=controller.page_title%></title>

它的效果很好,因为如果我在当前使用的任何控制器中没有page_title方法它回落到应用程序控制器中的默认值。但是,如果在我的用户控制器中,我希望它为新操作返回注册,但会退回到其他任何操作?有没有办法做到这一点?

It works well because if I don't have a page_title method in whatever controller I'm currently using it falls back to the default in the application controller. But what if in my users controller I want it to return "Signup" for the "new" action, but fall back for any other action? Is there a way to do that?

其次,其他人有没有其他方式在页面标题中使用rails?

Secondly, does anyone else have any other ways of doing page titles in rails?

推荐答案

我不同意其他答案,我相信标题不应该设置为每个动作,而是在视图本身。保持视图内的视图和控制器内的控制器逻辑。

I disagree with the other answers, I believe the title shouldn't be set per action, but rather within the view itself. Keep the view logic within the view and the controller logic within the controller.

在您的 application_helper.rb 中添加:

Inside your application_helper.rb add:

def title(page_title)
  content_for(:title) { page_title }
end

然后将它插入< title>

<title><%= content_for?(:title) ? content_for(:title) : "Default Title" %></title>

因此,当您在视图中时,您可以访问从控制器设置的所有实例变量,而您可以在那里设置。

So when you are in your views, you have access to all instance variables set from the controller and you can set it there. It keeps the clutter out of the controller as well.

<%- title "Reading #{@post.name}" %>

这篇关于Rails页面标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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