programing tip

Rails : 페이지 제목을 어떻게 바꾸나요?

itbloger 2020. 6. 5. 20:20
반응형

Rails : 페이지 제목을 어떻게 바꾸나요?


플러그인을 사용하지 않고 Rails 앱에서 페이지에 대한 사용자 정의 제목을 만드는 가장 좋은 방법은 무엇입니까?


당신의 견해에서 다음과 같이하십시오 :

<% content_for :title, "Title for specific page" %>
<!-- or -->
<h1><%= content_for(:title, "Title for specific page") %></h1>

레이아웃 파일은 다음과 같습니다.

<head>
  <title><%= yield(:title) %></title>
  <!-- Additional header tags here -->
</head>
<body>
  <!-- If all pages contain a headline tag, it's preferable to put that in the layout file too -->
  <h1><%= yield(:title) %></h1>
</body>

헬퍼 메소드로 content_forand yield(:title)을 캡슐화 할 수도 있습니다 (다른 사람들이 이미 제안했듯이). 그러나 이와 같은 간단한 경우에는 사용자 정의 도우미없이 필요한 코드를 특정보기에 직접 넣기를 좋아합니다.


사용하고 싶은 간단한 옵션이 있습니다.

레이아웃에서

<head>
  <title><%= @title %></title>
</head>

페이지 템플릿 상단 (첫 번째 줄)

<% @title="Home" %>

레이아웃 및 페이지 템플리트가 구문 분석되는 방식으로 인해 레이아웃이 렌더링되기 전에 @ title = "Home"이 평가됩니다.


모범 사례는 content_for를 사용하는 것입니다.

먼저 두 가지 도우미 메소드를 추가하십시오 (예 : app / helpers / application_helper.rb에 고정).

def page_title(separator = " – ")
  [content_for(:title), 'My Cool Site'].compact.join(separator)
end

def page_heading(title)
  content_for(:title){ title }
  content_tag(:h1, title)
end

그런 다음 레이아웃보기에서 간단히 사용할 수 있습니다.

<title><%= page_title %></title>

...보기 자체에서 :

<%= page_heading "Awesome" %>

이 방법을 사용하면 제목에 h1 태그를 붙이는 위치를 섞을 수 있고 컨트롤러에 성가신 @title 변수가 없어야합니다.


@opsb 및보다 완전한 @FouZ 형식 개선 :

에서 application.html.erb:

<title><%= @title || "Default Page Title" %></title>

erb 파일 또는 해당 컨트롤러에서 :

<% @title = "Unique Page Title" %>

살펴보기 content_for: http://railscasts.com/episodes/8


만족시키려는 사용 사례 또는 요구 사항에 대한 자세한 내용없이 몇 가지 대안을 생각할 수 있습니다.

1) 레이아웃 페이지 중 하나에서 제목을 전환하고 저장된 도우미 메소드를 사용하십시오. application_helper.rb

<title><%= custom_title %></title>

이 방법은 각 레이아웃 페이지에 고유 한 제목을 제공합니다.

2) Railscasts는 HEAD 태그 사이에 표시되는 부분을로드하기 위해 부분을 사용하도록 제안합니다.

3) load 이벤트 후에 제목을 변경해야하는 경우 javascript / ajax 호출을 사용하여 DOM을 조작하십시오.

title요소로 태그가 지정된 컨텐츠를 실제로 변경하고 싶지 않을 수도 있습니다 . 아마도 사용자는 사이트 탐색 경로와 관련하여 사용자가 항상 어디에 있는지 알 수 있도록 일종의 사이트 이동 경로가 필요할 수 있습니다. goldberg 플러그인 방식을 잘 수행했지만 동일한 기능을 수행하는 다른 방법이 있다고 확신합니다.


다음과 같이 페이지에서 호출 할 수있는 제목 변수를 제공하는 nifty_generator의 "nifty_layout"을 사용합니다.

<% title "Title of page" %>

또한 사용자 <% title "Title of page", false %>는 제목이 페이지 자체가 아닌 브라우저 제목에만 표시되도록 할 수 있습니다 .


컨트롤러의 before_filter에서 설정할 수도 있습니다.

# foo_controller.rb

class FooController < ApplicationController

  before_filter :set_title

  private

  def set_title
    @page_title = "Foo Page"
  end

end

# application.html.erb

<h1><%= page_title %></h1>

You can then set conditions in the set_title method to set a different titles for different actions in the controller. It's nice to be able to see all the relevant page titles within your controller.


The best/clean way to do this :

<title><%= @page_title or 'Page Title' %></title>

I use this plugin these Rails helpers I wrote: http://web.archive.org/web/20130117090719/http://henrik.nyh.se/2007/11/my-rails-title-helpers/


approach for page titling using content_for method and a partial

1 . partial name : _page_title.html.erb

<%content_for :page_title do %>
 <%=title%>
<%end%>

2 . Usage in application.html.erb inside title tag

   <title><%=yield :page_title %></title>

3 . Usage in respective *.html.erb excluding application.html.erb Just stick this in any .html.erb and supply title of the page

    e.g : inside index.html.erb

    <%=render '_page_title', title: 'title_of_page'%>

In short, I can write this down as follow

<%content_for :page_title do %><%= t :page_title, "Name of Your Page" %> <% end %>

I like opsb's method, but this method works too.

<% provide(:title,"ttttttttttttttttttZ") %>
<html>
  <head><title><%= yield(:title) %></title></head>
   <body></body>
</html>

I would like to add my pretty simple variant.

In the ApplicationController define this method:

  def get_title
    @action_title_name || case controller_name
                            when 'djs'
                              'Djs'
                            when 'photos'
                              'Photos'
                            when 'events'
                              'Various events'
                            when 'static'
                              'Info'
                            when 'club'
                              'My club'
                            when 'news'
                              'News'
                            when 'welcome'
                              'Welcome!'
                            else
                              'Other'
                          end
  end

After that you can call get_title from your layout's title tag. You can define more specific title for your page by defining @action_title_name variable in your actions.

참고URL : https://stackoverflow.com/questions/185965/rails-how-to-change-the-title-of-a-page

반응형