php CodeIgniter 创建布局/模板库
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16456819/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
CodeIgniter create a layout/template library
提问by ltdev
Before I begin I have to say that I have recently started learning CodeIgniter, so I'm sorry if I repeat this subject once again.
在开始之前,我不得不说我最近开始学习 CodeIgniter,所以如果我再次重复这个主题,我很抱歉。
In procedural php I would do something like this
在程序 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>
So I would like to do something similar and in CI. All pages/views will have the same main styles or scripts, but in some cases, some specific pages (like contact.php) may include, and onlyin these pages, some specific styles or scripts (like the validation.js).
所以我想在 CI 中做一些类似的事情。所有页面/视图都将具有相同的主要样式或脚本,但在某些情况下,某些特定页面(如 contact.php)可能包含且仅在这些页面中包含某些特定样式或脚本(如validation.js)。
I have found this videothat shows how to create a template/layout library using CI, but I'm not quite sure how I can apply this functionality to work properly.
我发现这个视频展示了如何使用 CI 创建模板/布局库,但我不太确定如何应用此功能才能正常工作。
回答by zion ben yacov
Put the bottom class in libraries/Layout.php (your app not the sys). In the autoload add the library:
将底层类放在 libraries/Layout.php (您的应用程序而不是 sys)中。在自动加载中添加库:
$autoload['libraries'] = array('layout');
In your controller just write $this->layout->render();
在你的控制器中只写 $this->layout->render();
The class will render the layout views/layouts/default.php
and the view views/$controller.views/$method.php
该类将呈现布局views/layouts/default.php
和视图views/$controller.views/$method.php
In the default layout just put
在默认布局中只需放置
<?php $this->load->view($view,$data); ?>
and thats it.
就是这样。
The code is
代码是
<?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);
}
}
?>
回答by cgwCode
I'm doing layout thing is like bellow.
我正在做布局的事情就像波纹管。
I get content to data['content'] variable.
我获取 data['content'] 变量的内容。
This is my controller.
这是我的控制器。
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);
}
This is my Layout.I'm using bootstrap layout.
这是我的布局。我正在使用引导程序布局。
<!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>
This is my content view
这是我的内容视图
<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>
回答by AbdulBasit
I use this, in older version of CodeIgniter and it works for version 3 as well.
我在旧版本的 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);
}
}
}
?>
and to call this in the controller I use:
并在我使用的控制器中调用它:
$this->layout->view('apps/apps', $data);
回答by Abdul Rehman
5 Simple Steps to create CodeIgniter Template:
创建 CodeIgniter 模板的 5 个简单步骤:
Step #1
第1步
Template.php @ libraries
Template.php @ 库
Step #2
第2步
Write following code
编写以下代码
/* 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 */
Step #3
第 3 步
open config/autoload.php at line 55 replace
在第 55 行打开 config/autoload.php 替换
$autoload['libraries'] = array('database', 'session','encrypt');
with this code
$autoload['libraries'] = array('database', 'session','encrypt', 'template');
Step #4
第四步
On my controller call template as
在我的控制器调用模板上
//start
$this->template->load(TEMPLATE_NAME, VIEW_NAME , $this->data);
//end
Step #5
第 5 步
On views create a file as custom_template.php And place there following code--
在视图上创建一个文件 custom_template.php 并在那里放置以下代码 -
//start
<?php $this->load->view('elements/header'); ?>
<div><?php echo $contents;?></div>
<?php $this->load->view('elements/footer'); ?>
//end
N.B.In views in elements folder create two files as header.phpAnd footer.php
注意在元素文件夹中的视图中创建两个文件作为header.php和footer.php
回答by Code Prank
I have achieved the same thing with the following:
我通过以下方式实现了同样的目标:
Put this code in your ./application/core/MY_Controller.php
file:
将此代码放入您的./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();
}
}
Create a layout folder inside ./application/views
directory and then create your files with the entire html in it. Just put the <?php echo $content; ?>
in that file where you want to put the dynamic content in it. Then in your controllers use $this->render();
and pass your file path and data. If you want to use a different layout for specific page just put the $this->layout = 'path_to_your_layout_file';
it will override the layout file to be used.
在./application/views
目录中创建一个布局文件夹,然后在其中创建包含整个 html 的文件。只需将 放入该<?php echo $content; ?>
文件中您想要将动态内容放入其中的位置。然后在您的控制器中使用$this->render();
并传递您的文件路径和数据。如果您想为特定页面使用不同的布局,只需放置$this->layout = 'path_to_your_layout_file';
它将覆盖要使用的布局文件。
回答by Rakan Nimer
I have struggled with a similar problem not long ago. My solution to it was the following : In your controller constructor create 2 arrays one of css files and one of js files and put in them the files common to all views. And in each function in the controller add to them logic specific files. For your example you'll have something like this :
不久前我也遇到过类似的问题。我的解决方案如下:在您的控制器构造函数中,创建 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()
{}
}
And in your view file you'll just iterate over the $css and $js array and include them one by one. You can extend that easily to include header and footer templates by pushing them into the page_data array.
在您的视图文件中,您只需遍历 $css 和 $js 数组并一一包含它们。您可以通过将页眉和页脚模板推送到 page_data 数组中来轻松扩展它以包含页眉和页脚模板。
I ended up switching to doing all the templating on the client-side with Backbone and using Code Igniter as a REST API only but this technique gave me relatively clean code for what I needed.
我最终转而使用 Backbone 在客户端完成所有模板,并仅将 Code Igniter 用作 REST API,但这种技术为我提供了我需要的相对干净的代码。