为了能更好的开发,需要基于codeigniter构建一个模版文件,这样就不需要在重复调用头部和底部文件了。这样开发者就只需关心各自的内容那块。
第一步,在application/library文件里创建一个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 set_arr($data) { foreach ($data as $key => $value) { $this->template_data[$key] = $value; } } function load($view = '', $view_data = array(), $template = 'template', $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); } }
将template.php放到autoload里面让他自动加载
$autoload['libraries'] = array('template');然后创建applicaton/config/style.php
<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); $config['js'] = array( 'demo' => array( 'jquery.min.js', 'jquery.uploadify.js', ), ); $config['css'] = array( 'demo' => array( 'global.css', 'style.css', 'uploadify.css', ), );然后在控制器里做如下调用
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Welcome extends CI_Controller { public function index() { $css = $this->config->item('demo','css'); $initialize = array('title'=>'众智云集','css'=>$css); $this->template->set_arr($initialize); //$this->template->set('title','124'); $data['author'] = array('author'=>'xp'); $data['js'] = $this->config->item('demo','js'); $this->template->load('user/about',$data); } }查看user/about试图文件
<?php echo $author['author'];?> <form> <input id="file_upload" name="file_upload" type="file" multiple="true"> </form> <?php echo output_js($js);?> <script type="text/javascript"> $(function() { .....; }); </script>查看template.php模版试图文件
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="keywords" content="" /> <meta name="description" content="" /> <title><?php echo $title; ?></title> <?php if(!empty($css) && is_array($css)): foreach($css as $v): echo "\t<link href=\"".base_url()."assets/css/{$v}\" rel=\"stylesheet\" type=\"text/css\" />\n"; endforeach; endif; ?> </head> <body> <div id="contents"> <?php echo $contents; ?> </div> <div id="footer"> </div> </body> </html>通过helper实现一个output_js的方法
/** * @name 输出js * @access public * @param Array $js * @return String */ if ( !function_exists( 'output_js' ) ) { function output_js($js) { $output = ''; if(!empty($js) && is_array($js)) { foreach($js as $v) { $output .= "<script type=\"text/javascript\" src=\"".base_url()."assets/js/{$v}\"></script>\n\t "; } } return $output; } }