added a trans filter (closes #85)

This commit is contained in:
Fabien Potencier
2010-08-13 19:15:57 +02:00
parent 13738f0082
commit 1eef779e00
4 changed files with 39 additions and 0 deletions
+1
View File
@@ -5,6 +5,7 @@ Backward incompatibilities:
* the odd and even filters are now tests:
{{ foo|odd }} must now be written {{ foo is(odd) }}
* added a "trans" filter
* added "test" feature (accessible via the "is" operator)
* removed the debug tag (should be done in an extension)
* fixed trans tag when no vars are used in plural form
@@ -881,6 +881,12 @@ The `plural` tag should provide the `count` used to select the right string.
Within the translatable string, the special `count` variable always contain
the count value (here the value of `apple_count`).
Within an expression or in a tag, you can use the `trans` filter to translate
simple strings or variables:
[twig]
{{ var|default(default_value|trans) }}
Expressions
-----------
+20
View File
@@ -243,3 +243,23 @@ Use the standard `xgettext` utility as you would have done with plain PHP
code:
xgettext --default-domain=messages -p ./locale --from-code=UTF-8 -n --omit-header -L PHP /tmp/cache/*.php
Complex Translations within an Expression or Tag
------------------------------------------------
Translations can be done with both the `trans` tag and the `trans` filter. The
filter is less powerful as it only works for simple variables or strings. For
more complex scenario, like pluralization, you can use a two-step strategy:
[twig]
{# assign the translation to a temporary variable #}
{% set default_value %}
{% trans %}
Hey {{ name }}, I have one apple.
{% plural apple_count %}
Hey {{ name }}, I have {{ count }} apples.
{% endtrans %}
{% endset %}
{# use the temporary variable within an expression #}
{{ var|default(default_value|trans) }}
+12
View File
@@ -20,6 +20,18 @@ class Twig_Extension_I18n extends Twig_Extension
return array(new Twig_TokenParser_Trans());
}
/**
* Returns a list of filters to add to the existing list.
*
* @return array An array of filters
*/
public function getFilters()
{
return array(
'trans' => new Twig_Filter_Function('gettext'),
);
}
/**
* Returns the name of the extension.
*