1010namespace Nette \Bridges \ApplicationLatte ;
1111
1212use Latte ;
13+ use Latte \Compiler \NodeHelpers ;
1314use Latte \Compiler \Nodes \Php ;
1415use Latte \Compiler \Tag ;
16+ use Latte \Engine ;
1517use Latte \Essential \Nodes \PrintNode ;
1618use Nette \Localization \Translator ;
1719
@@ -23,6 +25,7 @@ final class TranslatorExtension extends Latte\Extension
2325{
2426 public function __construct (
2527 private ?Translator $ translator ,
28+ private ?string $ key = null ,
2629 ) {
2730 }
2831
@@ -31,7 +34,7 @@ public function getTags(): array
3134 {
3235 return [
3336 '_ ' => [$ this , 'parseTranslate ' ],
34- 'translate ' => [ Nodes \TranslateNode::class, ' create ' ] ,
37+ 'translate ' => fn ( Tag $ tag ): \ Generator => Nodes \TranslateNode::create ( $ tag , $ this -> key ? $ this -> translator : null ) ,
3538 ];
3639 }
3740
@@ -46,6 +49,12 @@ public function getFilters(): array
4649 }
4750
4851
52+ public function getCacheKey (Engine $ engine ): mixed
53+ {
54+ return $ this ->key ;
55+ }
56+
57+
4958 /**
5059 * {_ ...}
5160 */
@@ -59,8 +68,24 @@ public function parseTranslate(Tag $tag): PrintNode
5968 if ($ tag ->parser ->stream ->tryConsume (', ' )) {
6069 $ args = $ tag ->parser ->parseArguments ();
6170 }
71+
6272 $ node ->modifier = $ tag ->parser ->parseModifier ();
6373 $ node ->modifier ->escape = true ;
74+
75+ if ($ this ->translator && $ this ->key ) {
76+ try {
77+ $ translation = $ this ->translator ->translate (
78+ NodeHelpers::toValue ($ node ->expression , constants: true ),
79+ ...NodeHelpers::toValue ($ args , constants: true ),
80+ );
81+ if (is_string ($ translation )) {
82+ $ node ->expression = new Php \Scalar \StringNode ($ translation );
83+ return $ node ;
84+ }
85+ } catch (\InvalidArgumentException ) {
86+ }
87+ }
88+
6489 array_unshift ($ node ->modifier ->filters , new Php \FilterNode (new Php \IdentifierNode ('translate ' ), $ args ->toArguments ()));
6590 return $ node ;
6691 }
0 commit comments