tonsky / tongue

Do-it-yourself i18n library for Clojure/Script
Eclipse Public License 1.0
307 stars 19 forks source link

Robustness for translations with incorrect placeholders #13

Closed jeroenheijmans closed 6 years ago

jeroenheijmans commented 6 years ago

First of all: thanks for a great project! It works like a charm.

TLDR Summary

We encountered a situation where a translation was off, e.g. "a {2} titled {3}", in a way that an error occurs when trying to render the translation in a Reagent component. Is there any way to have Tongue be robust (e.g. fall back or some such) for this scenario, or should I handle that in my own translate function instead?


Full issue with repro

To repro, first init a project:

lein new reagent-frontend tongtest

Add [tongue "0.2.3"] to your project.clj.

Then run it in the tongtest directory:

lein figwheel

This should open up a browser window with hot-reloading. Open up core.cljs, add [tongue.core :as tongue] to the :require section, and change the views section to this:

(def dicts { :en { :title "A {1} titled '{2}'."}})

(def translate (tongue/build-translate dicts))

(defn home-page []
  [:div [:h2 "Welcome to Reagent"] [:p (translate :en :title "foo" "bar")]])

So far so good, this should render just fine. Now change the first line to this:

(def dicts { :en { :title "A {2} titled '{3}'."}})

The result is that the entire page doesn't render anymore. In the console you get:

Error rendering component (in tongtest.core.home_page) Uncaught Error: Index out of bounds

Now, the error makes sense, but it's kinda harsh that if a translator makes a small mistake like this the entire application stops working.

My question: is there any way with the Tongue library to solve this? Or should I handle this myself in my translate function?

jeroenheijmans commented 6 years ago

FWIW, the workaround I'm currently trying out looks like this:

(def translate-inner (tongue/build-translate dicts))

(defn translate [locale key & rest]
  (try
    (apply translate-inner locale key rest)
    (catch :default _ key)))
tonsky commented 6 years ago

I think you’re right. Fixed in 0.2.4, check it out

jeroenheijmans commented 6 years ago

Works like a charm!