最佳实践:构建页眉和页脚的最佳方法是什么?

最佳实践:构建页眉和页脚的最佳方法是什么?

问题描述:

构建页眉和页脚的最佳方式是什么?你应该从控制器调用它,还是从视图文件中包含?我使用CodeIgniter,我想知道什么是这个的最佳实践。从控制器加载所有包含的视图文件,像这样?

What's the best way for constructing headers, and footers? Should you call it all from the controller, or include from the view file? I'm using CodeIgniter, and I'm wanting to know what's the best practice for this. Loading all the included view files from the controller, like this?

class Page extends Controller {

   function index()
   {
      $data['page_title'] = 'Your title';
      $this->load->view('header');
      $this->load->view('menu');
      $this->load->view('content', $data);
      $this->load->view('footer');
   }

}

或调用单个视图文件,并从那里调用页眉和页脚视图:

or calling the single view file, and calling the header and footer views from there:

//controller file    
class Page extends Controller {

   function index()
   {
      $data['page_title'] = 'Your title';
      $this->load->view('content', $data);

   }

}

//view file

<?php $this->load->view('header'); ?>

<p>The data from the controller</p>

<?php $this->load->view('footer'); ?>

我已经看到了这两种方式,但想要选择现在,路径。

I've seen it done both ways, but want to choose now before I go too far down a path.

您也可以尝试这样做 - 定义一个默认视图模板,然后拉入内容基于一个由控制器传递的变量(在我的例子中为'content')。

You could also try it this way -- define a default view template, which then pulls in the content based on a variable ('content' in my example) passed by the controller.

您的控制器中:

$data['content'] = 'your_controller/index';

// more code...

$this->load->vars($data);
$this->load->view('layouts/default');

然后定义所有页面的默认布局views / layouts / default.php

Then define a default layout for all pages e.g. views/layouts/default.php

// doctype, header html etc.

<div id="content">
    <?= $this->load->view($content) ?>
</div>

// footer html etc.

纯内容views / your_controller / index.php可能只包含从控制器/数据数组传递的变量

Then your views can just contain the pure content e.g. views/your_controller/index.php might contain just the variables passed from the controller / data array

<?= $archives_table ?>
<?= $pagination ?>
// etc.

有关CI wiki / FAQ 的更多详情 - (Q.如何在视图中嵌入视图?嵌套模板?...)

More details on the CI wiki/FAQ -- (Q. How do I embed views within views? Nested templates?...)