根据您的模板样式Mustache.php是实现您的目标的合适的库。
使用Composer。添加mustache/mustache
到项目的composer.json:
{
"require": {
"mustache/mustache": "~2.5"
}
}
用法:
if(isset($user->first_name) && isset($user->id)) {
$m = new Mustache_Engine;
return $m->render("Hello {{first_name}}, your ID is {{id}}", $user);
//will return: Hello John, your ID is 123.
}else {
//trigger error
}
更新1:
如果你的数据对象是一个Eloquent
例如,你可以使用下面的类在丢失变量的情况下自动抛出错误:
class MustacheData {
private $model;
public function __construct($model) {
$this->model = $model;
}
public function __isset($name) {
if (!isset($this->model->{$name})) {
throw new InvalidArgumentException("Missing $name");
}
return true;
}
public function __get($name) {
return $this->model->{$name};
}
}
用法:
try {
$m = new Mustache_Engine;
return $m->render("Hello {{first_name}}, your ID is {{id}}", new MustacheData($user));
}catch(InvalidArgumentException $e) {
//Handle the error
}
可能,这可能是有帮助吗? http://stackoverflow.com/questions/28554946/laravel-echoing-object-property-after-checking-for-existence –
你有没有考虑过使用[Twig](http://twig.sensiolabs.org/),可能是如果你只是将它用于变量,有点矫枉过正。 –
@Alok,因为我看到这是针对刀片式...我需要在模型/控制器中解析此字符串,而不是在模板中。 – Skatch