<title>ABCD</title>
这部分代码一般放在layout file中。其结果是所有的页面都使用相同的title, 这样不利于别人检索到你的网页。那么如何在不同的页面显示不同的title呢?
一.
我们先来看第一种方法,就是上一篇文章介绍的content_for 方法,
<% content_for :title do %>Recent Episodes<% end %>
然后在layout中:
<title>ASCIIcasts - <%= yield :title %></title>
但是这种做法不好的地方在于,每个页面都要有content_for 这个block才行。
二.
第二种方法就是使用实例变量,在controller中定义的实例变量是可以在template中自由使用的,当然,此处我们的实例变量可以直接在template中定义。
<% @page_title = "Recent Episodes" %>
然后在layout中:
<title>ASCIIcasts - <%= @page_title %></title>
三.
还有更好的方法,既然我们每个页面都会用到,那么不妨将content_for 做成一个方法,放在application_helpr.rb 中,
1. module ApplicationHelper
2. def title(page_title)
3. content_for(:title) { page_title }
4. end
5. end
这样,在每个template中,只需要调用这个方法,
1. <% title "Recent Episodes" %>
然后在layout中:
<title>ASCIIcasts - <%= yield :title %></title>
就可以了。
当然,如果你想有一个默认的title,那么可以使用:
<title>ASCIIcasts - <%= yield :title || “video.to_s”%></title>
这样,如果页面没有定义title,就会使用默认的title了
如果每一页都要在网页上显示出这个title来,那么显然显示title的html代码也是放在layout中最好了。
1. <div class="main">
2. <h2><%= yield(:title) %></h2>
3. <%= yield %>
4. </div>
这部分代码一般放在layout file中。其结果是所有的页面都使用相同的title, 这样不利于别人检索到你的网页。那么如何在不同的页面显示不同的title呢?
一.
我们先来看第一种方法,就是上一篇文章介绍的content_for 方法,
<% content_for :title do %>Recent Episodes<% end %>
然后在layout中:
<title>ASCIIcasts - <%= yield :title %></title>
但是这种做法不好的地方在于,每个页面都要有content_for 这个block才行。
二.
第二种方法就是使用实例变量,在controller中定义的实例变量是可以在template中自由使用的,当然,此处我们的实例变量可以直接在template中定义。
<% @page_title = "Recent Episodes" %>
然后在layout中:
<title>ASCIIcasts - <%= @page_title %></title>
三.
还有更好的方法,既然我们每个页面都会用到,那么不妨将content_for 做成一个方法,放在application_helpr.rb 中,
1. module ApplicationHelper
2. def title(page_title)
3. content_for(:title) { page_title }
4. end
5. end
这样,在每个template中,只需要调用这个方法,
1. <% title "Recent Episodes" %>
然后在layout中:
<title>ASCIIcasts - <%= yield :title %></title>
就可以了。
当然,如果你想有一个默认的title,那么可以使用:
<title>ASCIIcasts - <%= yield :title || “video.to_s”%></title>
这样,如果页面没有定义title,就会使用默认的title了
如果每一页都要在网页上显示出这个title来,那么显然显示title的html代码也是放在layout中最好了。
1. <div class="main">
2. <h2><%= yield(:title) %></h2>
3. <%= yield %>
4. </div>