Programing

Rails 3-페이지 제목을 설정하는 이상적인 방법

lottogame 2020. 10. 31. 09:10
반응형

Rails 3-페이지 제목을 설정하는 이상적인 방법


rails 3에서 페이지 제목을 설정하는 적절한 방법은 무엇입니까? 현재 다음을 수행하고 있습니다.

app / views / layouts / application.html :

<head>
  <title><%= render_title %></title>
  <%= csrf_meta_tag %>

app / helpers / application_helper.rb :

def render_title
  return @title if defined?(@title)
  "Generic Page Title"
end

app / controllers / some_controller.rb :

def show
  @title = "some custom page title"
end

위의 작업을 수행하는 다른 / 더 나은 방법이 있습니까?


간단한 도우미가 될 수 있습니다.

def title(page_title)
  content_for :title, page_title.to_s
end

레이아웃에서 사용하십시오.

<title><%= yield(:title) %></title>

그런 다음 템플릿에서 호출하십시오.

<% title "Your custom title" %>

도움이 되었기를 바랍니다 ;)


추가 기능 / 도우미를 만들 필요가 없습니다. 문서를 봐야합니다 .

애플리케이션 레이아웃

<% if content_for?(:title) %>
  <%= content_for(:title) %>
<% else %>
  <title>Default title</title>
<% end %>

특정 레이아웃에서

<% content_for :title do %>
  <title>Custom title</title>
<% end %>

apeacox의 솔루션이 저에게 적합하지 않다는 것을 발견했습니다 (Rails 3.0.3에서).

대신에 ...

에서 application_helper.rb:

def title(page_title, options={})
  content_for(:title, page_title.to_s)
  return content_tag(:h1, page_title, options)
end

레이아웃에서 :

<title><%= content_for(:title) %></title>

보기에서 :

<% title "Page Title Only" %>

또는:

<%= title "Page Title and Heading Too" %>

이것은 또한 우리가 제목의 존재를 확인하고 뷰가 하나를 지정하지 않은 경우에 기본 제목을 설정할 수 있도록합니다.

레이아웃에서 다음과 같이 할 수 있습니다.

<title><%= content_for?(:title) ? content_for(:title) : 'This is a default title' %></title>

이것이 내가 선호하는 방법입니다.

application_helper.rb

module ApplicationHelper
  def title(*parts)
    content_for(:title) { (parts << t(:site_name)).join(' - ') } unless parts.empty?
  end
end

views / layouts / application.html.erb

<title>
  <%= content_for?(:title) ? yield(:title) : t(:site_name) %>
</title>

config / locales / en.yml

en:
  site_name: "My Website"

이는 언어별로 번역 할 수있는 로케일의 사이트 이름으로 항상 돌아가는 좋은 이점이 있습니다.

그런 다음 다른 모든 페이지 (예 : 정보 페이지)에 간단히 다음을 입력 할 수 있습니다.

views / home / about.html.erb

<% title 'About' %>

해당 페이지의 결과 제목은 다음과 같습니다.

정보-내 웹 사이트

단순 :)


@akfalcon-비슷한 전략을 사용하지만 도우미없이 .. 응용 프로그램 컨트롤러에서 기본 @title을 설정 한 다음 레이아웃에서 <% = @ title %>를 사용합니다. 제목을 재정의하려면 컨트롤러 작업에서 다시 설정합니다. 마법은 없지만 잘 작동합니다. 메타 설명 및 키워드에 대해서도 동일합니다.

실제로 관리자가 Rails 코드를 업데이트하지 않고도 제목 등을 변경할 수 있도록 데이터베이스로 이동하는 것에 대해 생각하고 있습니다. 콘텐츠, 작업 및 컨트롤러로 PageTitle 모델을 만들 수 있습니다. 그런 다음 현재 렌더링중인 컨트롤러 / 액션에 대한 PageTitle을 찾는 도우미를 만듭니다 (controller_name 및 action_name 변수 사용). 일치하는 항목이 없으면 기본값을 반환합니다.

@apeacox-템플릿에서 제목을 설정하면 이점이 있습니까? 제목이 호출되는 작업과 직접 관련이 있으므로 컨트롤러에 배치하는 것이 더 나을 것이라고 생각합니다.


나는 이것을 선호한다 :

module ApplicationHelper
  def title(*page_title)
    if Array(page_title).size.zero?
      content_for?(:title) ? content_for(:title) : t(:site_name)
    else
      content_for :title, (Array(page_title) << t(:site_name)).join(' - ')
    end
  end
end

title인수없이를 호출 하면 제목의 현재 값 또는이 예제에서 "예제"가 될 기본값을 반환합니다.

title이 전달 된 값으로 설정하고, 인수라고합니다.

# layouts/application.html.erb
<title><%= title %></title>

# views/index.html.erb
<% title("Home") %>

# config/locales/en.yml
en:
  site_name: "Example"

You can also check this railscast. I think it will be very useful and give you basic start.

NOTE: In case you want more dynamic pages with pjax


I have a somewhat more complicated solution. I want to manage all of my titles in my locale files. I also want to include meaningful titles for show and edit pages such that the name of the resource is included in the page title. Finally, I want to include the application name in every page title e.g. Editing user Gustav - MyApp.

To accomplish this I create a helper in application_helper.rb which does most of the heavy lifting. This tries to get a name for the given action from the locale file, a name for the assigned resource if there is one and combines these with the app name.

# Attempt to build the best possible page title.
# If there is an action specific key, use that (e.g. users.index).
# If there is a name for the object, use that (in show and edit views).
# Worst case, just use the app name
def page_title
  app_name = t :app_name
  action = t("titles.#{controller_name}.#{action_name}", default: '')
  action += " #{object_name}" if object_name.present?
  action += " - " if action.present?
  "#{action} #{app_name}"
end

# attempt to get a usable name from the assigned resource
# will only work on pages with singular resources (show, edit etc)
def object_name
  assigns[controller_name.singularize].name rescue nil
end

You will need to add action specific texts in your locale files in the following form:

# en.yml 
titles:
  users:
    index: 'Users'
    edit: 'Editing'

And if you want to use meaningful resource names in your singular views you may need to add a couple of proxy methods, e.g.

# User.rb
def name
  username
end

I thought it will be good:

<title>
    <% if @title %>
      <%= @title %>
    <% else %>
      Your title
    <% end %>
</title>

And give a value to @title in your controller, or the title will be Your title


My answer is more simple:

locales/any_archive.yml:

pt-BR:
  delivery_contents:
    title: 'Conteúdos de Entregas'

  groups:
    title: 'Grupos'

And inside of application.html.slim:

title
  = "App Name: #{t("#{controller_name.underscore}.title")}"

There's a simple way to manipulate layout variables (title, description, etc.):

# app/views/application.html.erb
<title>
  <%= content_for :title || 'App default title' %>
</title>

# app/views/posts/index.html.erb
<%= content_for :title, 'List of posts' %>

And other pages will have App default title value for their titles


In application layout:

# app/views/layouts/application.html.erb

<title><%= (yield :title) || 'General title' %></title>

then in each view where you want a specific title:

<% content_for :title, 'Specific title' %>

There are already some good answers, but I'll add my simple approach. Add this to layouts/application.html

- if content_for?(:title)
  -title = "My site | #{content_for(:title)}"
-else
  -title = "My site | #{controller_name.titleize}"

You automagically get a nice names on all your views like "My site | Posts" -- or whatever the controller happens to be.

Of course, you can optionally set a title on a view by adding:

- content_for(:title, 'About')

and get a title like "My site | About".

참고URL : https://stackoverflow.com/questions/3059704/rails-3-ideal-way-to-set-title-of-pages

반응형