Search code examples
phpmustachemustache.php

How to use user defined function in mustache php


I have set up mustache php in my project.

echo $template->render(array(
     'data'=>$data, 
     'lang'=>$lang,
     'getMaritialStatus' => function($text, Mustache_LambdaHelper $helper) {
       return Common::getTextInHindi(ucwords(strtolower($helper->render($text))));
      }
));

and my user defined function is

public static function getTextInHindi($maritialStatus) {
      return $GLOBALS['lang'][$maritialStatus];
}

Now in my user defined function as you can see above when I try to print

print_r($GLOBALS['lang']['Married']);  //gives correct output
print_r($GLOBALS['lang'][$maritialStatus]); //gives undefined index error

even though $maritialStatus contains the string 'Married'.

Why is this happening


Solution

  • Turned out the value had to be trimmed:

     $GLOBALS['lang'][trim($maritialStatus)]
    

    At best trimming is already done before, so that it exists in the right format already:

    echo $template->render(array(
         'data'=>$data, 
         'lang'=>$lang,
         'getMaritialStatus' => function($text, Mustache_LambdaHelper $helper) {
           return trim(Common::getTextInHindi(ucwords(strtolower($helper->render($text)))));
          }
    ));