Skip to content
This repository has been archived by the owner on Dec 12, 2021. It is now read-only.

Commit

Permalink
translator function added
Browse files Browse the repository at this point in the history
  • Loading branch information
mkorkmaz committed Jul 21, 2017
1 parent 90104fe commit 724d92e
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 1 deletion.
3 changes: 3 additions & 0 deletions src/ExtensionsAbstract.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ abstract class ExtensionsAbstract
*/
protected function loadFunctions() : void
{
$this->extendForTranslator();
$this->extendForWidget();
$this->extendForSiteUrl();
$this->extendForGetUrl();
Expand All @@ -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.
*
Expand Down
18 changes: 18 additions & 0 deletions src/Twig/TwigExtensions.php
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
14 changes: 14 additions & 0 deletions test/TwigTest/TwigTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ class myTwigClass extends TestCase
'param1' => 1,
'param2' => 2,
'param3' => 3
],
'dictionary' => [
'Hello %s' => 'Merhaba %s'
]
];

Expand Down Expand Up @@ -83,6 +86,17 @@ public function shouldExtendForGetUrlSuccessfully()
$this->assertContains('<span>http://127.0.0.1/tr_TR/about</span>', $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
*/
Expand Down
3 changes: 2 additions & 1 deletion test/TwigTest/templates/translation.twig
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
<span id="translation">{{ _t('@loaded_language', translation) }}</span>
<span id="translation">{{ translate('Hello %s') | format('Selami') }}</span>
<span id="translation">{{ translate('Text missing in dictionary') }}</span>

0 comments on commit 724d92e

Please sign in to comment.