---
# System prepended metadata

title: i18n筆記
tags: [i18n]

---

---
title: i18n筆記
description: i18n
robots: noindex, nofollow
lang: zh-tw
dir: ltr
breaks: true
tags: i18n
disqus: hackmd
---

# i18n筆記

參考連結：
[Rails I18n 實作技巧 by 王信凱](https://hackmd.io/@Y7-oRV7UQKumWqYe3e0tOQ/HJarJWGd?print-pdf)
[使用env['rack.locale']要先裝這個gem](https://github.com/rack/rack-contrib)

## Rack::Locale Setting
`app/middlewares/rack/locale_without_setting.rb`
這邊設定`env['rack.locale']`

**不知這檔案是自動產生還是自己寫**
```ruby
require 'i18n'

class Rack::LocaleWithoutSetting < Rack::Locale
  def call(env)
    locale = accept_locale(env) || I18n.default_locale
    locale = env['rack.locale'] = locale.to_s
    status, headers, body = @app.call(env)
    headers['Content-Language'] = locale unless headers['Content-Language']
    [status, headers, body]
  end
end
```

有看到專案在這邊有設定middleware
`config/initializers/middlewares.rb`
```ruby=
require Rails.root.join('app', 'middlewares', 'theme_cacheable')
require Rails.root.join('app', 'middlewares', 'secure_cookie')
require Rails.root.join('app', 'middlewares', 'action_logger')

Cyberbiz::Application.configure do
  config.middleware.insert_after ActionDispatch::Session::CookieStore, ThemeCacheable
  config.middleware.insert_before ActionDispatch::Cookies, SecureCookie
  config.middleware.insert_before Rails::Rack::Logger, ActionLogger
  unless ENV['RACK_ATTACK_DISABLE'] == '1'
    config.middleware.insert_after Rack::Attack, Rack::LocaleWithoutSetting
  else
    config.middleware.insert_after Warden::Manager, Rack::LocaleWithoutSetting
  end
end
```

可以在 `app_controller.rb`寫
```ruby=
  before_action :set_locale unless Rails.env.production?
  
  private
  
  def set_locale
    I18n.locale = request.env['rack.locale']
  end
```

應該就可以偵測瀏覽器語言來轉換i18n語系？

## 當翻譯內含有html

參考連結:
https://stackoverflow.com/questions/3626038/use-html-inside-a-rails-translation-file
https://guides.rubyonrails.org/i18n.html#using-safe-html-translations

```ruby=
en:
  welcome: <b>welcome!</b>
  hello_html: <b>hello!</b>
  title:
    html: <b>title!</b>
```
在 key 上加上 `_html` 就可以進行轉義如果沒有加上在檢查safe html時就會被擋然後直接渲染 原始碼文字出現

```ruby
<div><%= t('welcome') %></div>
<div><%= raw t('welcome') %></div>
<div><%== t('welcome') %></div> // raw 跟 == 是一樣的
<div><%= t('hello_html') %></div>
<div><%= t('title.html') %></div>
```

![](https://i.imgur.com/CKxl9KX.png)

## 換行

可以使用`>` or `|` 兩個差別只有後者遇到空白就給換行符號`\n`前者在最後才有

![](https://i.imgur.com/X65P1LT.png)

## i18n in PORO
擴充 Module
`extend ActivedModel::Translation`

```ruby
class MyClass
  extend ActivedModel::Translation
end

MyClass.model_name.human
# => "MyClass"

MyClass.human_attribute_name(:my_attribute)
# => "My attribute"
```