ltd*_*dev 2 php layout templates codeigniter
在开始之前我不得不说我最近开始学习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>
Run Code Online (Sandbox Code Playgroud)
所以我想在CI中做类似的事情.所有页面/视图都具有相同的主要样式或脚本,但在某些情况下,某些特定页面(如contact.php)可能包含,并且仅在这些页面中包含某些特定样式或脚本(如validation.js).
我发现这个视频展示了如何使用CI创建模板/布局库,但我不太确定如何应用此功能才能正常工作.
将底层类放在libraries/Layout.php中(您的应用程序不是sys).在自动加载中添加库:
$autoload['libraries'] = array('layout');
Run Code Online (Sandbox Code Playgroud)
在你的控制器中只需写 $this->layout->render();
该类将呈现布局views/layouts/default.php和视图views/$controller.views/$method.php
在刚出现的默认布局中
<?php $this->load->view($view,$data); ?>
Run Code Online (Sandbox Code Playgroud)
就是这样.
代码是
<?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);
}
}
?>
Run Code Online (Sandbox Code Playgroud)