如何使模板中的变量可用? [英] How to make variables available in the template?

查看:21
本文介绍了如何使模板中的变量可用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下课程:

abstract class TheView
{
  public $template = NULL;
  public $variables = array();

  public function set($name, $value)
  {
    $this->variables[$name] = $value;
  }
  public function display()
  {
    include($this->template);
  }
}

模板文件是一个简单的 PHP 文件:

The template file is a simple PHP file:

<?php
echo $Message;
?>

如何让 TheView::$variables 中的所有变量在模板中可用(每个项目的键应该是变量的名称).

How can I make all the variables in TheView::$variables available in the template (the key of each item should be the name of the variable).

我已经尝试将所有变量添加到 $GLOBALS 中,但是没有用(我认为这是个坏主意).

I've already tried to add all variables to $GLOBALS but that didn't work (and I think it's a bad idea).

推荐答案

我总是这样做:

public function render($path, Array $data = array()){
    return call_user_func(function() use($data){
        extract($data, EXTR_SKIP);
        ob_start();
        include func_get_arg(0);
        return ob_get_clean();
    }, $path);
}

注意匿名函数和func_get_arg()调用;我使用它们来防止 $this 和其他变量污染"被传递到模板中.您也可以在包含之前取消设置 $data.

Note the anonymous function and func_get_arg() call; I use them to prevent $this and other variable "pollution" from being passed into the template. You can unset $data before the inclusion too.

如果您希望 $this 可用,只需直接从方法中 extract()include() 即可.

If you want $this available though, just extract() and include() directly from the method.

所以你可以:

$data = array('message' => 'hello world');
$html = $view->render('path/to/view.php', $data);

使用path/to/view.php:

<html>
    <head></head>
    <body>
        <p><?php echo $message; ?></p>
    </body>
</html>

如果您希望 View 对象通过,但不是从 render() 方法的范围内传递,请按如下方式更改:

If you want the View object passed, but not from the scope of the render() method, alter it as follows:

public function render($path, Array $data = array()){
    return call_user_func(function($view) use($data){
        extract($data, EXTR_SKIP);
        ob_start();
        include func_get_arg(1);
        return ob_get_clean();
    }, $this, $path);
}

$view 将是 View 对象的实例.它将在模板中可用,但只会公开公共成员,因为它位于 render() 方法的范围之外(保留私有/受保护成员的封装)

$view will be the instance of the View object. It will be available in the template, but will expose only public members, as it is from outside the scope of the render() method (preserving encapsulation of private/protected members)

这篇关于如何使模板中的变量可用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆