大网数据广告活动
PHP 语言与运行手册

Yaf_View_Interface::render · 渲染模板

· 52CE 我爱测

Yaf_View_Interface::render · 渲染模板

Yaf_View_Interface::render

(Yaf >=1.0.0)

Yaf_View_Interface::render — 渲染模板

说明

abstract public function Yaf_View_Interface::render(string $tpl, array $tpl_vars = NULL): string

渲染模板,并以字符串形式返回结果,而不是直接输出。

参数

tpl

模板的路径,相对于模板目录。

tpl_vars

仅供该模板使用的可选变量;它们会覆盖同名的已分配变量。

返回值

以字符串形式返回渲染结果,失败时返回 false。

示例

示例 #1 Yaf_View_Interface::render() 示例

<?php
class MyView implements Yaf_View_Interface
{
    private $tpl_dir;
    private $vars = array();

    public function __construct($template_dir, $options = null)
    {
        $this->tpl_dir = $template_dir;
    }

    public function assign($name, $value = null)
    {
        $this->vars[$name] = $value;
        return true;
    }

    public function display($tpl, $tpl_vars = null)
    {
        echo $this->render($tpl, $tpl_vars);
        return true;
    }

    public function render($tpl, $tpl_vars = null)
    {
        extract($this->vars);
        if ($tpl_vars !== null) {
            extract($tpl_vars);
        }
        ob_start();
        include $this->tpl_dir . "/" . $tpl;
        return ob_get_clean();
    }

    public function setScriptPath($template_dir)
    {
        $this->tpl_dir = $template_dir;
        return $this;
    }

    public function getScriptPath()
    {
        return $this->tpl_dir;
    }
}

/* 在 bootstrap 中将自定义视图引擎挂载到 dispatcher */
class Bootstrap extends Yaf_Bootstrap_Abstract
{
    public function _initView(Yaf_Dispatcher $dispatcher)
    {
        $dispatcher->setView(new MyView(APPLICATION_PATH . "/views"));
    }
}
?>

参见

来源:PHP Documentation Group · 作者与贡献记录 · CC BY 3.0。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
PHP Documentation Group
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。