Bart Friederichs
Bart Friederichs

Reputation: 33511

Adding parameter to lambda

I am using Mustache's Lambda's to implement translations in my templates.

My templates use these kind of tags:

<h1>{{#t}}Some translatable text{{/t}}</h1>

then, in my data I register a lambda to fetch the translation:

$info['t'] = function($text, $render) {
   return translate($text);
}

However, I would like to be able to set the locale in that lambda, but I don't seem to get it right:

$locale = "nl_NL";
$info['t'] = function($text, $render, $locale) {
   return translate($text, $locale);
}

doesn't work (obviously) because Mustache calls this lambda with two parameters. Trying with a default parameter doesn't work either:

$lc = "nl_NL";
$info['t'] = function($text, $render, $locale = $lc) {
   return translate($text, $locale);
}

Because you cannot use a variable as default.

How can I get this working?

Upvotes: 2

Views: 273

Answers (2)

Andrei Lupuleasa
Andrei Lupuleasa

Reputation: 2762

Use the use keyword to bind variables into the function's scope.

Closures may inherit variables from the parent scope. Any such variables must be declared in the function header [using use].

http://www.php.net/manual/en/functions.anonymous.php

$locale = "nl_NL";
$info['t'] = function($text, $render) use ($locale) {
   return translate($text, $locale);
}

Upvotes: 4

Rahul
Rahul

Reputation: 18557

I think some problem here with the scope of variable,

$lc = "nl_NL";
$info['t'] = function($text, $render) use($lc) {
   return translate($text, $lc);
}

should solve your problem

Upvotes: 3

Related Questions