【问题标题】:How to load MVC views into main template file如何将 MVC 视图加载到主模板文件中
【发布时间】:2011-09-10 00:31:33
【问题描述】:

我正在开发自己的 MVC 框架。以下是我目前拥有的示例控制器。

我有办法将模型加载到我的控制器中并查看文件。

我还想为我的网站提供不同的模板选项。我的模板将只是一个页面布局,它将从我的控制器创建的视图插入到我的模板文件的中间。

/**
 * Example Controller
 */
class User_Controller extends Core_Controller {

    // domain.com/user/id-53463463
    function profile($userId)
    {
        // load a Model
        $this->loadModel('profile');  

        //GET data from a Model
        $profileData = $this->profile_model->getProfile($userId);

        // load view file and pass the Model data into it
        $this->view->load('userProfile', $profileData);
    }

}

这里是模板文件的一个基本思路...

DefaultLayout.php

<!doctype html>
<html lang="en">
<head>
</head>
<body>



Is the controller has data set for the sidebar variable, then we will load the sidebar and the content
<?php if( ! empty($sidebar)) { ?>

<?php print $content; ?>

<?php print $sidebar; ?>


If no sidebar is set, then we will just load the content
<?php } else { ?>

<?php print $content; ?>

<?php } ?>

</body>
</html>

另一个没有任何页眉、页脚和其他任何内容的模板可用于 AJAX 调用

EmptyLayout.php

<?php
$content
?>

我正在寻找有关如何加载我的主模板文件,然后在我的主布局文件的内容区域中包含和查看文件的想法?

在示例布局文件中,您可以看到内容区域有一个名为 $content 的变量。我不确定如何使用视图内容填充它,以插入到我的主布局模板中。如果您有任何想法,请发布示例

【问题讨论】:

    标签: php model-view-controller templates


    【解决方案1】:

    有点像

    function loadView ($strViewPath, $arrayOfData)
    {
    // This makes $arrayOfData['content'] turn into $content
    extract($arrayOfData);
    
    // Require the file
    ob_start();
    require($strViewPath);
    
    // Return the string
    $strView = ob_get_contents();
    ob_end_clean();
    return $strView;
    }
    

    然后与

    一起使用
    $sidebarView = loadView('sidebar.php', array('stuff' => 'for', 'sidebar' => 'only');
    $mainView = loadView('main.php', array('content' => 'hello',, 'sidebar' => $sidebarView);
    

    【讨论】:

    • 这太好了,我总是在控制器/模型中格式化和设置内容输出,然后使用file_get_contents,然后用str_replace替换视图中的占位符,例如:&lt;p&gt;{content}&lt;/p&gt;。好东西
    猜你喜欢
    • 1970-01-01
    • 2017-02-24
    • 1970-01-01
    • 1970-01-01
    • 2011-10-22
    • 1970-01-01
    • 2012-12-12
    • 2014-12-02
    • 2018-05-15
    相关资源
    最近更新 更多