erlydtl/erlydtl — pull request #132 by seriyps (2014-02-16 21:28:35+00:00)
Title: Consistent compile-time {%trans%}

This patch allow to translate `{%trans%}` and `_(..)` to multiple langs in compile time using the same techinique, as `blocktrans` do: put translated string for each language directly in to template code. It reuses `blocktrans_fun` and `blocktrans_locales` options (see https://github.com/erlydtl/erlydtl/issues/131#issuecomment-35090982). So, when `blocktrans_fun` is specified, it will be called not only on `blocktrans` blocks, but on `trans` and `_(..)`; when not specified - code for runtime translation generated (see also https://github.com/erlydtl/erlydtl/pull/130).
This will generate following code:

```erlang
1> BTransFun = fun(A, B) -> iolist_to_binary([A, "-", B]) end.
2> erlydtl:compile(
<<"11{%blocktrans%}222{%endblocktrans%}333{%trans var%}444{%trans '666'%}77">>,
t, [debug_info, {out_dir, "/tmp"}, force_recompile, {binary_strings, false},
{blocktrans_fun, BTransFun},
{blocktrans_locales, ["en", "ru"]}]).

3> t:render([], [{locale, "en"}]).
{ok,["11",["222-en"],"333","undefined","444","555-en","66"]}
4> t:render([], [{locale, "ru"}]).
{ok,["11",["222-ru"],"333","undefined","444","555-ru","66"]}
```

```erlang
["11",
case _CurrentLocale of
"en" -> ["222-en"];
"ru" -> ["222-ru"];
_ -> ["222"]
end,
"333",
erlydtl_runtime:translate(
erlydtl_runtime:find_value(var,
_Variables,
['...']),
_TranslationFun,
erlydtl_runtime:find_value(var,
_Variables,
['...'])),
"444",
case _CurrentLocale of
"ru" -> "666-ru";
"en" -> "666-en";
_ -> "666"
end,
"77"]
```
When runtime translation used (no `blocktrans_fun`)
```erlang
1> erlydtl:compile(
<<"11{%blocktrans%}222{%endblocktrans%}333{%trans var%}444{%trans '555'%}66">>,
t, [debug_info, {out_dir, "/tmp"}, force_recompile, {binary_strings, false}]).

2> t:render([{var, "wasd"}], [{translation_fun, fun(Key) -> binary_to_list(BTransFun(Key, "ru")) end}]).
{ok,["11",["222"],"333","wasd-ru","444","666-ru","77"]}
3> t:render([{var, "wasd"}], [{translation_fun, fun(Key) -> binary_to_list(BTransFun(Key, "en")) end}]).
{ok,["11",["222"],"333","wasd-en","444","666-en","77"]}
4> t:render([{var, "wasd"}], [{translation_fun, fun(Key) -> binary_to_list(BTransFun(Key, "fr")) end}]).
{ok,["11",["222"],"333","wasd-fr","444","666-fr","77"]}
```
```erlang
["11",
["222"], % <- this one will be changed by #130
"333",
erlydtl_runtime:translate(
erlydtl_runtime:find_value(var,
_Variables,
['...']),
_TranslationFun,
erlydtl_runtime:find_value(var,
_Variables,
['...'])),
"444",
erlydtl_runtime:translate("555",
_TranslationFun,
"555"),
"66"]
```
The main advantage - you don't need gettext_server to render the same .beam in multiple languages.