如何在codeigniter中获取整个项目的默认模板/布局?

时间:2012-04-14 02:28:10

标签: php codeigniter templates layout view

有人能告诉我如何在codeigniter中为整个项目实现默认模板/布局吗?

我发现的一种方法是Templating with Code Igniter (CI Forums)

还有其他方法吗?任何人都可以发布完整的示例代码吗?

3 个答案:

答案 0 :(得分:3)

制作一个布局视图。有点像这样:

<html>
  <head>
    <title>My awesome site</title>
  </head>
  <body>
    <?= $this->load->view('shared/header') ?>
    <?= $this->load->view($partial) ?>
    <?= $this->load->view('shared/footer') ?>
  </body>
</html>

然后在你的控制器中执行以下操作:

$this->data['partial'] = 'pages/index';
$this->load->view('layout/layout', $this->data);

如果你有一个MY_Controller文件,你可以在那里创建一个方法:

function load_view($partial)
{
  $this->data['partial'] = $partial;
  $this->load->view('layout/layout', $this->data);
}

然后在继承自MY_Controller的控制器中,您可以使用:

$this->load_view('pages/index'); // pages/index will be loaded in the layout

答案 1 :(得分:2)

我知道其中一种方法是为您的网站/项目创建页眉和页脚视图。

application/views/template/header.php
application/views/template/footer.php

然后按照您的意愿安排其他页面。

application/views/users/login.php

在你的控制器中,你会做这样的事情

<?php
    class Blah extends CI_Controller
    {
        public function __construct()
        {
            parent::__construct();
        }

        public function index()
        {
            $this->load->view('template/header');
            $this->load->view('users/login');
            $this->load->view('template/footer');
        }
    }

我偶然发现了一个有用的小模板库,这使得它更加简单。我发现它没有像输入其他方式那样灵活。

http://maestric.com/doc/php/codeigniter_template

EDIT :: 我应该为模板提供一些示例代码,所以在这里你去

的header.php

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>Lovely Title</title>
    </head>
    <body>
        <h1>Check This Out!!1!</h1>
        <div class="container">

footer.php

        </div>
    </body>
</html>

答案 2 :(得分:0)

您始终可以加载具有其他视图的视图并实现您想要的效果。

其他更好的方法是使用支持模板继承的模板引擎,如

在CodeIgniter中使用它们相当容易,因为CI的库有很多实现。

相关问题