CodeIgniter创建布局/模板库

时间:2013-05-09 07:39:38

标签: php codeigniter templates layout

在开始之前,我必须说我最近开始学习CodeIgniter,所以如果我再次重复这个主题,我很抱歉。

在程序php中我会做这样的事情

// the header.php
<!DOCTYPE html>
<html>
<head>
      <meta name="description" content="blah blah">
      <title>My Site</title>
      <link href="css/main.css" rel="stylesheet" media="screen">
<php? if($current_page == 'about.php'): ?>
      <link href="css/secondary.css" rel="stylesheet" media="screen"> // or some embed styles (<stlye> ... </style>)
   <?php endif; ?> 


      <script src="http://code.jquery.com/jquery.js"></script>
      <script src="js/main_script.js"></script>

      <php? if($current_page == 'contact.php'): ?>
      <script src="js/validation.js"></script>
      <?php endif; ?>
</head>
<body>
     // end of header.php

     include('template/header.php');

     <h1>Heading1</h1>    
     <p>Lorem Ipsum...</p>

     include('template/footer.php');

    //footer.php
    //maybe some js and here
</body>
</html>

所以我想在CI中做类似的事情。所有页面/视图都具有相同的主要样式或脚本,但在某些情况下,某些特定页面(如contact.php)可能包含这些页面中的 ,某些特定样式或脚本(如validation.js)。

我发现这个video显示了如何使用CI创建模板/布局库,但我不太确定如何应用此功能才能正常工作。

6 个答案:

答案 0 :(得分:5)

将底层类放在libraries / Layout.php中(您的应用程序不是sys)。在自动加载中添加库:

$autoload['libraries'] = array('layout');

在您的控制器中,只需撰写$this->layout->render();

即可

该类将呈现布局views/layouts/default.php和视图views/$controller.views/$method.php

在默认布局中添加

<?php $this->load->view($view,$data); ?>

就是这样。

代码是

<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');

class Layout
{
    public $data = array();
    public $view = null;
    public $viewFolder = null;
    public $layoutsFodler = 'layouts';
    public $layout = 'default';
    var $obj;

    function __construct()
    {
        $this->obj =& get_instance();
    }

    function setLayout($layout)
    {
        $this->layout = $layout;
    }
    function setLayoutFolder($layoutFolder)
    {
        $this->layoutsFodler = $layoutFolder;
    }

    function render()
    {

        $controller = $this->obj->router->fetch_class();
        $method = $this->obj->router->fetch_method();
        $viewFolder = !($this->viewFolder) ? $controller.'.views' : $this->viewFolder . '.views';
        $view = !($this->view) ? $method : $this->view;

        $loadedData = array();
        $loadedData['view'] = $viewFolder.'/'.$view;
        $loadedData['data'] = $this->data;

        $layoutPath = '/'.$this->layoutsFodler.'/'.$this->layout;
        $this->obj->load->view($layoutPath, $loadedData);
    }
}
?>

答案 1 :(得分:1)

我做布局的事情就像吼叫。

我了解数据[&#39;内容&#39;]变量。

这是我的控制器。

    class Article extends MY_Controller {

        function __construct() {
            parent::__construct();
            $this->load->model('article_model');
        }

        public function index() {

            $data['allArticles']    =   $this->article_model->getAll(); 

            $data['content']        =   $this->load->view('article', $data, true);
            $this->load->view('layout', $data);

        }

这是我的布局。我正在使用bootstrap布局。

    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="utf-8">
            <meta http-equiv="X-UA-Compatible" content="IE=edge">
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <meta name="description" content="">
            <meta name="author" content="">
            <title>Starter Template for Bootstrap</title>
            <base href="<?php echo base_url(); ?>" />

            <!-- Bootstrap core CSS -->
            <link href="assets/bootstrap3.0.1/css/bootstrap.min.css" rel="stylesheet">

            <!-- Custom styles for this template -->
            <!--    <link href="starter-template.css" rel="stylesheet">-->

            <!-- Just for debugging purposes. Don't actually copy this line! -->
            <!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->

            <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
            <!--[if lt IE 9]>
              <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
              <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
            <![endif]-->
        </head>

        <body>

            <div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
                <div class="container">
                    <div class="navbar-header">
                        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                            <span class="sr-only">Toggle navigation</span>
                            <span class="icon-bar"></span>
                            <span class="icon-bar"></span>
                            <span class="icon-bar"></span>
                        </button>
                        <a class="navbar-brand" href="#"> Article Management System</a>
                    </div>
                    <div class="collapse navbar-collapse">
                        <ul class="nav navbar-nav">
                            <li class="active"><a href="">Home</a></li>
                            <li class="dropdown">
                                <a class="dropdown-toggle" data-toggle="dropdown" href="#"> Admin <span class="caret"></span></a>
                                <ul class="dropdown-menu">
                                    <li><a href="article/add">Add Article</a></li>
                                    <li><a href="article">All Article</a></li>
                                </ul>
                            </li>
                        </ul>
                    </div><!--/.nav-collapse -->
                </div>
            </div>

            <div class="container" style="margin-top: 80px;">

                <?php echo $content; ?>

            </div><!-- /.container -->


            <!-- Bootstrap core JavaScript
            ================================================== -->
            <!-- Placed at the end of the document so the pages load faster -->
            <script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
            <script src="assets/bootstrap3.0.1/js/bootstrap.min.js"></script>
        </body>
    </html>        

这是我的内容视图

    <div class="row">

        <div class="col-xs-12 col-sm-12 col-md-12">

            <div class="page-header">
                <h4>All Articles </h4>
            </div>

        </div>

        <div class="col-xs-12 col-sm-12 col-md-12">

            <table class="table table-striped table-bordered">
                <thead>
                    <tr>
                        <th>Title</th>
                        <th>Description</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($allArticles as $row) { ?>
                    <tr>
                        <td><?php echo $row->title; ?></td>
                        <td><?php echo substr($row->description,0,100); ?> ....</td>
                        <td></td>
                    </tr>
                    <?php } ?>
                </tbody>
            </table>

        </div>
    </div>

答案 2 :(得分:0)

我通过以下方式实现了同样的目标:

将此代码放入./application/core/MY_Controller.php文件中:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

    class MY_Controller extends CI_Controller
    {
        protected $layout = 'layout/main';

        public function __construct()
        {
            parent::__construct();
        }

        protected function render($file = NULL, &$viewData = array(), $layoutData = array())
        {
            if( !is_null($file) ) {
                $data['content'] = $this->load->view($file, $viewData, TRUE);
                $data['layout'] = $layoutData;
                $this->load->view($this->layout, $data);
            } else {
                $this->load->view($this->layout, $viewData);
            }

            $viewData = array();
        }
   }

./application/views目录中创建一个布局文件夹,然后在其中创建包含整个html的文件。只需将<?php echo $content; ?>放在要放置动态内容的文件中即可。然后在您的控制器中使用$this->render();并传递您的文件路径和数据。如果您想为特定页面使用不同的布局,只需放置$this->layout = 'path_to_your_layout_file';它将覆盖要使用的布局文件。

答案 3 :(得分:0)

不久前,我一直在努力解决类似的问题。我的解决方案如下: 在你的控制器构造函数中创建2个数组,一个css文件和一个js文件,并在其中放入所有视图共有的文件。 并且在控制器的每个函数中添加逻辑特定文件。 对于你的例子,你会有这样的事情:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Home extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->page_data = array();
        $this->page_data['css']=array('main.css','bootstrap.css');
        $this->page_data['js']=array('main.js','bootstrap.js');
    }
    public function about()
    {
       array_push($this->page_data['css'],'secondary.css');
       $this->load->view('main_layout',$this->page_data)
    }
    public function contact()
    {}


 }

在你的视图文件中,你只需迭代$ css和$ js数组并逐个包含它们。 您可以通过将它们推入page_data数组轻松扩展它以包含页眉和页脚模板。

我最终切换到使用Backbone在客户端进行所有模板操作,并仅使用Code Igniter作为REST API,但这种技术为我提供了相对干净的代码。

答案 4 :(得分:0)

我在旧版本的CodeIgniter中使用它,它也适用于版本3.

<?php  
if (!defined('BASEPATH')) exit('No direct script access allowed');

class Layout
{

    var $obj;
    var $layout;

    function Layout($layout = "layout_main")
    {
        $this->obj =& get_instance();
        $this->layout = $layout;
    }

    function setLayout($layout)
    {
      $this->layout = $layout;
    }

    function view($view, $data=null, $return=false)
    {
        $loadedData = array();
        $loadedData['content_for_layout'] = $this->obj->load->view($view,$data,true);

        if($return)
        {
            $output = $this->obj->load->view($this->layout, $loadedData, true);
            return $output;
        }
        else
        {
            $this->obj->load->view($this->layout, $loadedData, false);
        }
    }
}
?>

并在我使用的控制器中调用它:

$this->layout->view('apps/apps', $data);

答案 5 :(得分:0)

创建CodeIgniter模板的5个简单步骤:

第1步

Template.php @ libraries

步骤#2

编写以下代码

/* Start of file Template.php */
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Template {
        var $template_data = array();
        function set($name, $value)
        {
            $this->template_data[$name] = $value;
        }
        function load($template = '', $view = '' , $view_data = array(), $return = FALSE)
        {               
            $this->CI =& get_instance();
            $this->set('contents', $this->CI->load->view($view, $view_data, TRUE));         
            return $this->CI->load->view($template, $this->template_data, $return);
        }
}
/* End of file Template.php */
/* Location: ./system/application/libraries/Template.php */

步骤#3

打开config / autoload.php 在第55行替换

$autoload['libraries'] = array('database', 'session','encrypt');
with this code
$autoload['libraries'] = array('database', 'session','encrypt', 'template');

步骤#4

在我的控制器调用模板上

//start
$this->template->load(TEMPLATE_NAME, VIEW_NAME , $this->data);
//end

步骤#5

观点 创建一个文件custom_template.php 并在下面放置代码 -

//start
<?php $this->load->view('elements/header'); ?>
<div><?php echo $contents;?></div>
<?php $this->load->view('elements/footer'); ?>
//end

N.B。在elements文件夹的视图中创建两个文件 header.php footer.php