Getting Text and Currency Working for Multiple Language Support (Page 1 of 5 )
Localizing Numbers and Currencies
Next, we’ll show you how to change the product catalog to display the correctly formatted page count and price for the currently selected locale.
Open app/views/catalog/catalog.rhtml in your editor and append .localize to the code that prints the page count:
<h2>by <%= @book.authors.map{|a| a.name}.join(", ") %></h2> <%= image_tag url_for_file_column(:book, :cover_image) ? unless @book.cover_image.blank? % > <dl> <dt>Price</dt> <dd>$<%= @book.price -%></dd> <dt>Page count</dt> <dd><%= @book.page_count.localize -%></dd>
This will now localize the page count. For example, a book having 400000 pages will be displayed as 400,000.
To localize the price field, we first need to modify the Book model ( app/models/book.rb ), as shown here:
class Book < ActiveRecord::Base acts_as_taggable
has_and_belongs_to_many :authors belongs_to :publisher has_many :cart_items has_many :carts, :through => :cart_items
translates :title, :blurb acts_as_ferret :fields => [:title, :author_names] composed_of :price_localized, :class_name => "Globalize::Currency", :mapping => [ %w(price cents) ]
This adds the new field price_localized to the model, which will be properly formatted when used in a view.
Next, change the catalog view ( app/views/catalog/show.rhtml ) to use the new field:
<h2>by <%= @book.authors.map{|a| a.name}.join(", ") %></h2> <%= image_tag url_for_file_column(:book, :cover_image) ? unless @book.cover_image.blank? % > <dl> <dt>Price</dt> <dd>$<%= @book.price_localized -%></dd> <dt>Page count</dt> <dd><%= @book.page_count.localize -%></dd>
Now if you access the book details page ( http://localhost:3000/catalog/show/1 ), you should see the following:
-------------------------------------------- Price $10,000.00 Page count 400,000 --------------------------------------------
Please enable JavaScript to view the comments powered by Disqus. blog comments powered by