diff --git a/src/ExtensionsAbstract.php b/src/ExtensionsAbstract.php
index bbd6c8b..873ffce 100644
--- a/src/ExtensionsAbstract.php
+++ b/src/ExtensionsAbstract.php
@@ -16,6 +16,7 @@ abstract class ExtensionsAbstract
*/
protected function loadFunctions() : void
{
+ $this->extendForTranslator();
$this->extendForWidget();
$this->extendForSiteUrl();
$this->extendForGetUrl();
@@ -24,6 +25,8 @@ protected function loadFunctions() : void
$this->extendForVarDump();
}
+ abstract protected function extendForTranslator() : void;
+
/**
* Extend for function getUrl that returns url path for an alias.
*
diff --git a/src/Twig/TwigExtensions.php b/src/Twig/TwigExtensions.php
index b783ea6..dbecf0d 100644
--- a/src/Twig/TwigExtensions.php
+++ b/src/Twig/TwigExtensions.php
@@ -27,6 +27,24 @@ public function __construct(Environment $twig, array $config)
$this->loadFunctions();
}
+ protected function extendForTranslator() : void
+ {
+ $dictionary = $this->config['dictionary'];
+ $filter = new \Twig_SimpleFunction(
+ 'translate',
+ function (
+ $string
+ ) use ($dictionary) {
+ if (array_key_exists($string, $dictionary)) {
+ return $dictionary[$string];
+ }
+ return $string;
+ },
+ array('is_safe' => array('html'))
+ );
+ $this->twig->addFunction($filter);
+ }
+
protected function extendForGetUrl() : void
{
$filter = new Twig_SimpleFunction(
diff --git a/test/TwigTest/TwigTest.php b/test/TwigTest/TwigTest.php
index 63f448c..de3a9c9 100644
--- a/test/TwigTest/TwigTest.php
+++ b/test/TwigTest/TwigTest.php
@@ -30,6 +30,9 @@ class myTwigClass extends TestCase
'param1' => 1,
'param2' => 2,
'param3' => 3
+ ],
+ 'dictionary' => [
+ 'Hello %s' => 'Merhaba %s'
]
];
@@ -83,6 +86,17 @@ public function shouldExtendForGetUrlSuccessfully()
$this->assertContains('http://127.0.0.1/tr_TR/about', $result, "Twig didn't correctly get url.");
}
+
+ /**
+ * @test
+ */
+ public function shouldExtendForTranslatorSuccessfully()
+ {
+ $result = $this->view->render('translation.twig');
+ $this->assertContains('Merhaba Selami', $result, "Twig didn't correctly translate.");
+ $this->assertContains('Text missing in dictionary', $result, "Twig didn't correctly translate.");
+ }
+
/**
* @test
*/
diff --git a/test/TwigTest/templates/translation.twig b/test/TwigTest/templates/translation.twig
index 42a4724..fcca6e7 100644
--- a/test/TwigTest/templates/translation.twig
+++ b/test/TwigTest/templates/translation.twig
@@ -1 +1,2 @@
-{{ _t('@loaded_language', translation) }}
\ No newline at end of file
+{{ translate('Hello %s') | format('Selami') }}
+{{ translate('Text missing in dictionary') }}
\ No newline at end of file