Ruby-GetText-Package HOWTO for CGI/ERB

ruby-gettext-howto-cgi

HOWTO using Ruby-GetText-Package with CGI.

See also samples in ruby-gettext-x.x.x/samples/cgi/.

A table of contents

  • Using Ruby-GetText with CGI
  • Using Ruby-GetText with ERB
  • Using Ruby-GetText with other Template engines or split HTML files

Using Ruby-GetText with CGI

This is very simple/easy sample. It's same as normal applications.

See a sample below. The domainname is "index" and the mo file is installed to "/app/locale/#{lang}/LC_MESSAGES/".

require 'gettext/cgi'

include GetText

set_output_charset("UTF-8")
bindtextdomain("index", "/app/locale")

print "Content-type:text/html; charset=UTF-8\n\n"

puts %Q[<html><head>
 <meta http-equiv="content-type" content="text/html; charset=UTF-8">
 <title>]
puts _("Sample script for CGI/ERB and Ruby-GetText-Package")
puts  "</title><body>"

puts "<h1>" + _("Hello World") + "</h1>"
puts "</body></html>"

In this sample, output charset is UTF-8 forcely.

If you want to set the charset flexibility, you can do as follows:

require 'gettext/cgi'

include GetText

bindtextdomain("index", "/app/locale")

print "Content-type:text/html; charset=#{Locale.charset}\n\n"

puts %Q[<html><head>
 <meta http-equiv="content-type" content="text/html; charset=#{Locale.charset}">
 <title>]
puts _("Sample script for CGI/ERB and Ruby-GetText-Package")
puts  "</title><body>"

puts "<h1>" + _("Hello World") + "</h1>"
puts "</body></html>"

But I don't recommand this way and recommand to set output charset to 'UTF-8'. Because if the WWW browser doesn't return HTTP_ACCEPT_CHARSET, it won't work as you think. And also if you want to store the data to DB, you need to convert the charset carefully.

How to get the locale information from WWW browser

The locale value is get from the order by "lang" value of QUERY_STRING > "lang" value of Cookie > HTTP_ACCEPT_LANGUAGE value > "en" (English). And the charset is set order by HTTP_ACCEPT_CHARSET > "UTF-8".

Your application needs to set "lang" value of QUERY_STRING or Cookies properly by itself.

Notice: If you set locale/charset using GetText functions such as GetText.output_charset=, the setting has forced and the WWW browser requests are ignored.

Last modified:2009/03/29 00:47:17
Keyword(s):
References:[Ruby-GetText-Package HOWTO] [Ruby-GetText for Ruby on Rails] [Ruby-GetText-Package document for Developers]