【问题标题】:Assign variable to php template将变量分配给php模板
【发布时间】:2015-05-30 10:59:28
【问题描述】:

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

但是在没有 Smarty 的情况下,使用 .php 文件模板如何正确地完成? 例如,我使用该结构:

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

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

【问题讨论】:

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


    【解决方案1】:

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

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

    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>
    

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-26
      • 2020-04-07
      • 1970-01-01
      • 2014-06-22
      • 1970-01-01
      • 1970-01-01
      • 2013-12-24
      • 2018-01-13
      相关资源
      最近更新 更多