简体   繁体   中英

Creating custom templates for rendering common pages

I am new to codeigniter, I would like to know how I can use custom templates for rendering common pages like header, footer, sidepanel,etc. along with data to the pages.

class Template {

function show($view)
{
    <?php $this->load->view('header'); ?>
    <?php $this->load->view($view,$data); ?>
    <?php $this->load->view('footer',$data); ?>
}
} 

here is the sample what i meant for . can any one help please.

Do not call 3 views in one controller function because they will limit you. instead call only one view which calls 3 other view.

this is your plan:

$this->load->view('header');
$this->load->view($view,$data);
$this->load->view('footer',$data);

the problem is that your header view will open some HTML tags which will be closed in footer view, such as div#container . That will make your code illegible.

My suggestion is:

$main_data['a']=...
$main_data['b']=...
$main_data['c']=...
$this->general_view('myview',$main_data);

protected function general_view($main_view,$main_data)
{
  $data['main_data']=$main_data;
  $data['main_view']=$main_view;
  $this->load->view('general_view',$data);
}

inside general view:

<HTML>
  <HEAD>
    ....
  </HEAD>
  <BODY>
    <?$this->load->view('header');?>
    <div id="container">
      <?$this->load->view($main_view,$main_data);?>
    </div>
    <?$this->load->view('footer',$data);?>
  </BODY>
<HTML>

使用模板库,这是一个很好的: 模具 ,或者使用: 这样

Yes you can, just add a file inside views named masterpage.php, then use the following code:

<html>
<head>
</head>
<body>
<div class='menu'>My Menu here</div>
<div class='content'>
<?php echo $content; ?>
</div>
</body>
</html>

then your views shoud be like

<?php
  ob_start();
?>
content

<?php
  $content= ob_get_contents(); 
  ob_end_clean(); 
  include("application/views/masterpage.php");
?>

I hope it helps.

You can extend a abstractClass to get an hierarchy index:

AbstractClass:

class AbstractController extends CI_Controller
{  
     var $_template;

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

     function index()
     {
        $this->load->view('header');
        $this->load->view($this->_template);
        $this->load->view('footer',$data);
     }
} 

Home Controller:

class Home extends AbstractController
{
   function __construct()
   {
        parent::__construct();

        $this->_template = "home/home_view";
   }
}

When you access site.com/home you gonna override $this->_template and with path for home view, and call index() from abstract controller

Good Lucky

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM