Internationalization

Contents

  1. Internationalization

Internationalization

Luminius template comes with Tower dependency which provides you functionality for internationalization and translation.

First, we need to create a dictionary map such as the one below.

(def tconfig
  {:fallback-locale :en-US
   :dictionary
   {:en-US   {:page {:title "Here is a title"
                     :content "Time to start building your site."}
              :missing  "<Missing translation: [%1$s %2$s %3$s]>"}
    :fr-FR {:page {:title "Voici un titre"
                   :content "Il est temps de commencer votre site."}}
    }})

We can then add the Tower middleware wrapper to our handler with the above config in our middleware namespace in the wrap-base function.

(defn wrap-base [handler]
  (-> handler
      #(taoensso.tower.ring/wrap-tower-middleware % {:tconfig tconfig})
      ...))

The middleware will use the accept-language header to infer the preferred locale for the client. The middleware will append two keys to the request. The first key is :t and it points to the function that handles the translations. The second key is :locale and it points to the locale that was inferred by the middleware.

Alternatively, possible to supply a custom locale-selector function to the middleware:

(defn my-selector [req]
  (when (= (:remote-addr req) "127.0.0.1") :en))

(defn wrap-base [handler]
  (-> handler
      #(wrap-tower-middleware % {:tconfig tconfig
                                :locale-selector my-selector})
      ...))

The locale middleware will use the first available locale from the following options:

(:locale request)
(when-let [ls locale-selector] (ls request))
(:locale session)
(:locale params)
(locale-from-headers headers)
fallback-locale

With the middleware setup, we can now use translations in our pages as seen below.

(ns mysite.routes.home
  (:use compojure.core)
  (:require [i18ntest.layout :as layout]
            [i18ntest.util :as util]
            [taoensso.tower :refer [t]]))

(defn home-page [{:keys [locale tconfig]}]
  (layout/render
    "home.html" {:title   (t locale tconfig :page/title)
                 :content (t locale tconfig :page/content)}))

(defn about-page []
  (layout/render "about.html"))

(defroutes home-routes
  (GET "/" req (home-page req))
  (GET "/about" [] (about-page)))

More information is available on the Github page for the project.