如何在PHP中实现类似smarty的显示?
因此,它会自动替换index.html中的如何在PHP中实现类似smarty的显示?,php,smarty,templating,Php,Smarty,Templating,因此,它会自动替换index.html中的$variables,从而节省大量的echo?您可以使用类似以下内容: $smarty->assign('name',$value); $smarty->display("index.html"); 摘自上一个问题 // assigns the output of a file into a variable... function get_include_contents($filename, $data='') { if (is
$variables
,从而节省大量的echo
?您可以使用类似以下内容:
$smarty->assign('name',$value);
$smarty->display("index.html");
摘自上一个问题
// assigns the output of a file into a variable...
function get_include_contents($filename, $data='') {
if (is_file($filename)) {
if (is_array($data)) {
extract($data);
}
ob_start();
include $filename;
$contents = ob_get_contents();
ob_end_clean();
return $contents;
}
return false;
}
$data = array('name'=>'Ross', 'hobby'=>'Writing Random Code');
$output = get_include_contents('my_file.php', $data);
// my_file.php will now have access to the variables $name and $hobby
在模板中
class Templater {
protected $_data= array();
function assign($name,$value) {
$this->_data[$name]= $value;
}
function render($template_file) {
extract($this->_data);
include($template_file);
}
}
$template= new Templater();
$template->assign('myvariable', 'My Value');
$template->render('path/to/file.tpl');
使用中的Templater类,可以将render函数更改为使用正则表达式
function replace_var($matches){
global $data;
return $data[$matches[1]];
}
preg_replace_callback('/{$([\w_0-9\-]+)}/', 'replace_var');
和以下模板文件:
function render($template_file) {
$patterns= array();
$values= array();
foreach ($this->_data as $name=>$value) {
$patterns[]= "/\\\$$name/";
$values[]= $value;
}
$template= file_get_contents($template_file);
echo preg_replace($patterns, $values, $template);
}
......
$templater= new Templater();
$templater->assign('myvariable', 'My Value');
$templater->render('mytemplate.tpl');
这是我的变量$myvariable
将导致:
这是我的变量我的值
免责声明:实际上还没有运行这个来看看它是否有效!请参阅关于preg#u replace的PHP手册,示例2:您描述的功能由PHP函数处理,例如:
<html>
<body>
This is my variable <b>$myvariable</b>
</body>
</html>
但我强烈建议您使用Sergey或RageZ发布的类之一,因为否则您将重新发明轮子,PHP中有大量的低姿态和高端模板类,实际上,对很多人来说:)@Mask:在你的最后一个问题上,有些用户已经实现了这一点……@Mask:那么,去看看你为什么不使用smarty的
显示
?@RC:从我的观点来看,他正在重新编码smarty…@RageZ,我也从你所指问题的回答中看到了这一点,但我不明白为什么..多亏了这个用户的代码,有人能理解它是如何替换$myvariable的变量的吗?我只是看不到这一部分。
<html>
<body>
This is my variable <b>$myvariable</b>
</body>
</html>
// Source: http://www.php.net/manual/en/function.extract.php
$size = "large";
$var_array = array("color" => "blue", "size" => "medium", "shape" => "sphere");
extract($var_array, EXTR_PREFIX_SAME, "wddx");
echo "$color, $size, $shape, $wddx_size\n";