빠른 참조

Rails 국제화 (i18n) 치트시트

Rails 국제화(i18n) 빠른 참조 가이드: 텍스트 번역, 로컬라이즈된 날짜, 복수형 처리, 지연 스코프 조회 및 YAML 로케일 사전.

· 게시일

Rails 국제화(i18n) 프레임워크는 표준 YAML 사전 카탈로그를 통해 문자열, 숫자, 통화 및 날짜의 로컬라이제이션을 제공합니다.

기본 번역 및 날짜 헬퍼

<!-- 키 번역 -->
<%= t('welcome.title') %>

<!-- 현재 컨트롤러/액션 기반의 지연 스코프 번역 -->
<!-- app/views/articles/index.html.erb 에서 articles.index.heading 조회 -->
<%= t('.heading') %>

<!-- 날짜 및 시간 로컬라이징 -->
<%= l(Time.now, format: :short) %>
<%= l(Date.today, format: :long) %>

변수 보간 및 복수형 처리

# config/locales/en.yml
en:
  greetings:
    hello: "Hello, %{name}!"
  inbox:
    unread_messages:
      one: "You have 1 unread message."
      other: "You have %{count} unread messages."
      zero: "You have no unread messages."

템플릿 내에서:

<%= t('greetings.hello', name: current_user.name) %>
<%= t('inbox.unread_messages', count: @unread_count) %>

현재 로케일 설정

ApplicationController 에서:

class ApplicationController < ActionController::Base
  before_action :set_locale

  private

  def set_locale
    I18n.locale = params[:locale] || I18n.default_locale
  end

  def default_url_options
    { locale: I18n.locale }
  end
end

Active Record 모델 번역

en:
  activerecord:
    models:
      user: "Customer"
    attributes:
      user:
        email: "Email Address"
        role: "Account Role"

뷰 내에서:

<%= User.model_name.human %>
<!-- => "Customer" -->

<%= User.human_attribute_name(:email) %>
<!-- => "Email Address" -->

참고 자료

관련 주제