预先,您可以通过这种方式构建您的视图:
首先在您的视图文件夹中创建一个模板
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<meta content="MajidGolshadi" name="author">
<?php echo $html_head; ?>
<title></title>
</head>
<body>
<div id="content">
<?php echo $content; ?>
</div>
<div id="footer">
<?php echo $html_footer; ?>
</div>
</body>
</html>
第二
创建一个库来自动加载您的视图
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Template
{
private $data;
private $js_file;
private $css_file;
private $CI;
public function __construct()
{
$this->CI =& get_instance();
$this->CI->load->helper('url');
// default CSS and JS that they must be load in any pages
$this->addJS( base_url('assets/js/jquery-1.7.1.min.js') );
$this->addCSS( base_url('assets/css/semantic.min.css') );
}
public function show( $folder, $page, $data=null, $menu=true )
{
if ( ! file_exists('application/views/'.$folder.'/'.$page.'.php' ) )
{
show_404();
}
else
{
$this->data['page_var'] = $data;
$this->load_JS_and_css();
$this->init_menu();
if ($menu)
$this->data['content'] = $this->CI->load->view('template/menu.php', $this->data, true);
else
$this->data['content'] = '';
$this->data['content'] .= $this->CI->load->view($folder.'/'.$page.'.php', $this->data, true);
$this->CI->load->view('template.php', $this->data);
}
}
public function addJS( $name )
{
$js = new stdClass();
$js->file = $name;
$this->js_file[] = $js;
}
public function addCSS( $name )
{
$css = new stdClass();
$css->file = $name;
$this->css_file[] = $css;
}
private function load_JS_and_css()
{
$this->data['html_head'] = '';
if ( $this->css_file )
{
foreach( $this->css_file as $css )
{
$this->data['html_head'] .= "<link rel='stylesheet' type='text/css' href=".$css->file.">". "\n";
}
}
if ( $this->js_file )
{
foreach( $this->js_file as $js )
{
$this->data['html_head'] .= "<script type='text/javascript' src=".$js->file."></script>". "\n";
}
}
}
private function init_menu()
{
// your code to init menus
// it's a sample code you can init some other part of your page
}
}
第三
在每个控制器构造函数中加载您的库,然后使用此库自动加载您的视图
要在你的视图中加载额外的 js,你可以通过这种方式使用addJS 方法:
$this->template->addJS("your_js_address");
对于CSS:
$this->template->addCSS("your_css_address");
并使用show 方法调用您的视图文件来显示您的页面内容
$this->template->show("your_view_folder", "view_file_name", $data);
希望这些代码对你有帮助