假设我有这个数组:
$meta = array(
'name' => 'John Doe',
'age' => 16,
'e-mail' => 'john.doe@doedoe.com'
);
如何允许用户使用这些变量自定义布局?(并且能够捕获错误(。这是我目前的想法:
extract($meta,EXTR_OVERWRITE);
$string = "Hi, I am $name. This is an $undefined_variable";
但是,它无法捕获未定义的变量。
这个怎么样?
$string = "Hi, I am {{name}}. This is an {{undefined_variable}}";
foreach ($meta as $key => $value) {
$string = str_replace('{{' . $key . '}}', $value, $string);
}
或者,如果您可以将 {{name}}
等直接作为 $meta
中的键,那么:
$string = "Hi, I am {{name}}. This is an {{undefined_variable}}";
$string = str_replace(array_keys($meta), array_values($meta), $string);
或者,如果无法将密钥放在原始密钥中,则可以使用{{...}}
密钥创建并缓存$meta
:
$metaTokens = array();
foreach ($meta as $key => $value) {
$metaTokens['{{' . $key . '}}'] = $value;
}
然后,如果你想简单地隐藏未定义的变量,现在你应该已经填写了所有定义的变量,所以{{..}}
里面的任何其他东西都应该是一个未定义的变量:
$string = preg_replace('/{{.+?}}/', '', $string);
你可以根据
这篇文章创建一个模板类(我尽量避免使用魔术方法(:
class Template
{
protected $parameters = array();
protected $filename = null;
public function __construct( $filename )
{
$this->filename = $filename;
}
public function bind($name, $value)
{
$this->parameters[$name] = $value;
}
public function render()
{
extract( $this->parameters );
error_reporting(E_ALL ^ E_NOTICE);
ob_start();
include( $this->filename );
error_reporting(~0); // -1 do not work on OSX
return ob_get_clean();
}
}
基本上,您在渲染输出之前禁用警告,然后再次启用它们。这将允许您呈现文件,即使尚未定义某些变量。