将变量分配给php模板

时间:2015-05-30 10:59:28

标签: php html variables templates model-view-controller

我通常使用Smarty模板引擎,所以我将数据库问题和其他逻辑从HTML模板文件中分离出来,然后通过函数$smarty->assign('variableName', 'variableValue');将收到的PHP变量分配到Smarty中,然后用HTML标记显示正确的模板文件,然后我可以在该模板中使用我指定的变量。

但如果没有Smarty,.php文件tempaltes将如何正确完成? 例如,我使用这种结构:

_handlers / Handler_Show.php

$arData = $db->getAll('SELECT .....');
include_once '_template/home.php';

_template / home.php

<!DOCTYPE html>
<html>
<head>
  ....
</head>
<body>
  ...
  <?php foreach($arData as $item) { ?>
    <h2><?=$item['title']?></h2>
  <?php } ?>
  ...
</body>
</html>

这是工作。但我听说这样做并不是最好的主意。 那么这种方法是否正确?或者也许有其他方式来组织它? 给我建议,pelase。

1 个答案:

答案 0 :(得分:1)

以您的示例中的方式包含模板并不是最好的主意,因为模板代码在包含它的同一名称空间中执行。在您的案例中,模板可以访问数据库连接和其他应该与视图分开的变量。

为了避免这种情况,您可以创建类Template:

<强>的template.php

<?php
class Template
{
    private $tplPath;

    private $tplData = array();

    public function __construct($tplPath)
    {
        $this->tplPath = $tplPath;
    }

    public function __set($varName, $value)
    {
        $this->tplData[$varName] = $value;
    }

    public function render()
    {
        extract($this->tplData);
        ob_start();
        require($this->tplPath);
        return ob_get_clean();
    }
}

<强> _handlers / Handler_Show.php

<?php
// some code, including Template class file, connecting to db etc..
$tpl = new Template('_template/home.php');
$tpl->arData = $db->getAll('SELECT .....');
echo $tpl->render();

<强> _template / home.php

<?php
<!DOCTYPE html>
<html>
<head>
  ....
</head>
<body>
  ...
  <?php foreach($arData as $item): ?>
    <h2><?=$item['title']?></h2>
  <?php endforeach; ?>
  ...
</body>
</html>

截至目前,模板无法访问全局命名空间。当然,仍然可以使用全局关键字, 或访问模板对象私有数据(使用$ this变量),但这比解决方案好得多 直接包含模板。

您可以查看现有的模板系统源代码,例如plates