在CodeIgniter的视图中包含视图的最佳方法 [英] Best method of including views within views in CodeIgniter

查看:200
本文介绍了在CodeIgniter的视图中包含视图的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始一个大的codeigniter项目,并想尝试为内容片段创建一些可重复使用的迷你视图,如可能显示在不同的页面/控制器上的数据循环。



最好从主控制器的视图中调用视图?如果是,如何?或者我应该从控制器调用迷你视图,从而将视图的代码传递到主视图?

解决方案

其他视图称为嵌套视图
在CodeIgniter中包含嵌套视图的两种方法:



1。在控制器中加载嵌套视图



预先加载视图并传递到其他视图。首先把它放在控制器中:

 <?php 
//TRUE内容,而不是立即显示
$ data ['menu'] = $ this-> load-> view('menu',NULL,TRUE);
$ this-> load-> view('home',$ data);
?>

然后将<?= $ menu?> 在您希望菜单出现的时候。



2。从视图中加载视图



首先将其放在控制器中:

 <?php 
$ this-> load-> view('home');
?>

然后将它放在 /application/views/home.php view:

 <?php $ this-& > 

< p>其他首页内容...< / p>关于最好的方法,我喜欢第一种方法超过第二种方法,因为使用第一种方法,我不'不得不混淆代码,它不像包括 php。虽然间接两者是相同的,但第一种方法更清楚,比第二个更清洁!


I'm starting a large codeigniter project and would like to try to create some reusable 'mini' views for snippets of content like loops of data which may be displayed on different pages/controllers.

Is it better to call the views from within the main controller's view? If so, how? Or should I call the 'mini view' from the controller and thus pass the view's code to the main view?

解决方案

Views within other views are called Nested views. There are two ways of including nested views in CodeIgniter:

1. Load a nested view inside the controller

Load the view in advance and pass to the other view. First put this in the controller:

<?php
// the "TRUE" argument tells it to return the content, rather than display it immediately
$data['menu'] = $this->load->view('menu', NULL, TRUE);
$this->load->view ('home', $data);
?>

Then put <?=$menu?> in your view at the point you want the menu to appear.

2. Load a view "from within" a view

First put this in the controller:

<?php
  $this->load->view('home');
?>

Then put this in the /application/views/home.php view:

<?php $this->view('menu'); ?>

<p>Other home content...</p>

About best method, I prefer the 1st method over 2nd one, because by using 1st method I don't have to mix up code, it is not like include php. Although indirectly both are same, the 1st method is clearer & cleaner than 2nd one!

这篇关于在CodeIgniter的视图中包含视图的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆