【问题标题】:How to use user defined function in mustache php如何在 mustache php 中使用用户定义的函数
【发布时间】:2018-11-26 09:38:03
【问题描述】:

我已经在我的项目中设置了mustache php

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

我的用户定义函数是

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

现在在我的用户定义函数中,当我尝试打印时,您可以在上面看到

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

即使$maritialStatus 包含字符串'Married'

为什么会这样

【问题讨论】:

  • 会不会是大小写不对,所以变量$martialStatus的值为married?在这种情况下,您可能会写 $GLOBALS['lang'][ucfirst($maritialStatus)]$GLOBALS['lang'][ucfirst(strtolower($maritialStatus))]
  • 另一种选择是您必须修剪值:$GLOBALS['lang'][trim($maritialStatus)]
  • 修剪完成了工作,谢谢......愚蠢的错误

标签: php mustache mustache.php


【解决方案1】:

原来值必须被修剪:

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

最好的修剪之前已经完成,因此它已经以正确的格式存在:

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

【讨论】:

  • 你可以在这里帮助我的另一件事......我将 $lang 传递给我的胡子模板,这也是我的 $GLOBALS['lang'] 数组......所以而不是调用函数有什么我可以在这里使用 $lang 的吗?
  • 当您更改函数中的值时 (ucwords(strtolower($helper->render($text))) 我不知道如何,但也许如果您调试 $Globals['lang'] 所需的值已经以正确的格式存在。
猜你喜欢
  • 2011-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-19
  • 1970-01-01
相关资源
最近更新 更多