如何在PHP中实现像smarty这样的显示?

时间:2009-11-19 06:09:19

标签: php smarty templating

$smarty->assign('name',$value);
$smarty->display("index.html");

这样它会自动替换index.html中的$variables,从而节省了大量的echo

4 个答案:

答案 0 :(得分:1)

您可以使用以下内容:

// 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

答案 1 :(得分:1)

取自上一个问题

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');
模板中的

<?= $foobar ?>

会打印foobar ....如果您需要制作自己的语法,可以使用preg_replace_callback

例如:

function replace_var($matches){
    global $data;
    return $data[$matches[1]];
}
preg_replace_callback('/{$([\w_0-9\-]+)}/', 'replace_var');

答案 2 :(得分:1)

使用previous answer中的Templater类,您可以更改渲染函数以使用正则表达式

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');

以下模板文件:

<html>
<body>
This is my variable <b>$myvariable</b>
</body>
</html>

渲染:

  

这是我的变量我的价值

免责声明:实际上没有运行它,看它是否有效!请参阅preg_replace上的PHP手册,示例#2:http://php.net/manual/en/function.preg-replace.php

答案 3 :(得分:0)

您描述的功能由extract php函数处理,例如:

// 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";

但是我强烈建议你使用Sergey或RageZ发布的其中一个类,否则你将重新发明轮子,PHP中有许多低分析和高端模板类,实际上很多人都是:)