ActionView、Application.html.erb 和 HTML head 标签

Joh*_*son 1 ruby meta ruby-on-rails title actionview

我有一个关于 Ruby on Rails、ActionView、Application.html.erb 和 HTML head 标签的使用的简单问题。

我知道 application.html.erb 用于在您网站上的所有页面上显示内容。

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="description" content="My desciprtion.">
  <meta name="robots" content="index,follow">
  <title><%= @title %></title>
    <%= stylesheet_link_tag    "application", media: "all", "data-turbolinks-track" => true, :cache => "cache/all" %>
    <%= javascript_include_tag "application", :async => true, "data-turbolinks-track" => true, :cache => "cache/all" %>
    <%= csrf_meta_tags %>
</head>
Run Code Online (Sandbox Code Playgroud)

这意味着,上面的代码会显示在我的所有网页上。

现在,我一直在阅读有关 SEO 的内容,它建议为每个网页使用单独的描述元标记,以告诉搜索引擎页面的内容。我要问你的问题是

您是否可以在 Rails 中自定义各个页面,例如

page1.html.erb
page2.html.erb
page3.html.erb
Run Code Online (Sandbox Code Playgroud)

并在其中包含 HTML head 标签?

我使用 Ruby on Rails 已经有一段时间了,但我从未在视图页面中看到过 head 标签。

我还没有看到关于此事的身体标签。

我用过

<% @title = "Page Title" %>
Run Code Online (Sandbox Code Playgroud)

声明页面的单独标题。这相当于 HTML 标题标签。

是否有类似的东西来声明每个网页的描述?

Bro*_*tse 6

您可以将标题更改为:

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <%= yield :meta %>
  <meta name="robots" content="index,follow">
  <title><%= yield :title %></title>
    <%= stylesheet_link_tag    "application", media: "all", "data-turbolinks-track" => true, :cache => "cache/all" %>
    <%= javascript_include_tag "application", :async => true, "data-turbolinks-track" => true, :cache => "cache/all" %>
    <%= csrf_meta_tags %>
</head>
Run Code Online (Sandbox Code Playgroud)

然后根据您的观点,您可以这样做:

<% content_for :meta do %>
  <meta name="description" content="blah">
<% end %>

<% content_for :title, 'My title' %>
Run Code Online (Sandbox Code Playgroud)