R18n for Sinatra
Install
gem install sinatra-r18n
How To
- Create translations dir ./i18n/.
- Add file with translation to ./i18n/ with language code in file
name (for example, en.yml for English or en-us.yml USA
English dialect). For example, ./i18n/en.yml:
post: friends: Post only for friends tags: Post tags is %1 comments: !!pl 0: No comments 1: One comment n: %1 comments html: !!html <b>Don't escape HTML</b>
- Add R18n to your Sinatra application:
require 'sinatra/r18n'
If your application inherits from Sinatra::Base also add:
class YourApp < Sinatra::Base register Sinatra::R18n set :root, File.dirname(__FILE__)
- Add locale to your URLs. For example:
get '/:locale/posts/:id' do @post = Post.find(params[:id]) haml :post end
Or save locale in session, when user change it:
before do session[:locale] = params[:locale] if params[:locale] end
- Use translation messages in views. For example in HAML:
%p= t.post.friends %p= t.post.tags(@post.tags.join(', ')) %h2= t.comments(@post.comments.size) - Print localized time and numbers. For example:
l @post.created_at, :human
- Print available translations. For example in HAML:
%ul - r18n.available_locales.each do |locale| %li %a{ href: "/#{locale.code}/" }= locale.title
Configuration
You can change default locale and translations dir:
set :default_locale, 'ru' set :translations, './translations'