How to load MVC views into main template file

2019-04-06 14:08发布

I am working on my own MVC framework. Below is an example controller I have so far.

I have a way of loading models into my controller and also view files.

I am wanting to also have different template options for my site. My template will just be a page layout that inserts the views that are created from my controller into the middle of my template file.

/**
 * 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);
    }

}

Here is a basic idea of the template file...

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>

Another Template without any header, footer, anything else, can be used for AJAX calls

EmptyLayout.php

<?php
$content
?>

I am looking for ideas on how I can load my main template file and then include and view files into the content area of my main layout file?

In the sample layout file, you can see that the content area has a variable called $content. I am not sure how I can populate that with the views content, to be inserted into my main layout template. If you have any ideas, please post sample

1条回答
成全新的幸福
2楼-- · 2019-04-06 14:52

Something a little bit like

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;
}

Then use with

$sidebarView = loadView('sidebar.php', array('stuff' => 'for', 'sidebar' => 'only');
$mainView = loadView('main.php', array('content' => 'hello',, 'sidebar' => $sidebarView);
查看更多
登录 后发表回答