skeay 发表于 2011-2-25 22:32:14

视图中传递重复编写变量如何解决

本帖最后由 skeay 于 2011-2-25 22:33 编辑

管理员你好:
我用CI的时候
index.php

class Index extends Controller{
    function __construct()
    {
      parent::Controller();
      
    }
   
    function Index()
    {   
      $config['title'] ="Phnome' home";
      $config['body'] = 'includes/body';
      $config['left'] = 'includes/left';
      $config['url'] = base_url();
      
      
      $this->load->view('template',$config);
    }
}

blog.php

<?php

class Blog extends Controller{
   
    function index()
    {
      $config['title'] ="Phnome's Blog";
      $config['body'] = 'includes/blog';
      $config['left'] = 'includes/left';
      $config['url'] = base_url();
      
      $this->load->view('template',$config);
    }
}

像这些每次每个页面都要重复写然后传给视图,里面好多重复的数据,
有什么好的方法能减少这种重复呢
       $config['title'] ="Phnome's Blog";
      $config['body'] = 'includes/blog';
      $config['left'] = 'includes/left';
      $config['url'] = base_url();
谢谢各位大大百忙之中抽时间来论坛

skeay 发表于 2011-2-25 22:48:37

不想用inclue()包一个写好的配置文件,这要不好

Hex 发表于 2011-2-26 00:06:24

可以在视图里嵌套视图。
还可以使用 HMVC。
HMVC 可以用我发布的扩展。

skeay 发表于 2011-2-26 11:40:04

恩 好的谢谢

skeay 发表于 2011-2-26 12:23:15

首先定义一个自己的类库

<?php
class vars
{
    var $CI;
    function vars(){
      $this->CI = & get_instance();
      //变量可以在这里定义,或者来自配置文件,也可以去数据库中查
      $variable = array('abc'=>'asdfasdf');
      $this->CI->load->vars($variable);
    }
}

修改config/autoload.php,自动加载上面的类。

$autoload['libraries'] = array('database','session','vars');


使用方法:
控制器

<?php
class Test extends Controller {
    function __construct()
    {
      parent::Controller();   
    }
    function index()
    {
      $this->load->view('test_view');
    }
}


视图,test_view.php

<?php
echo $abc;
页: [1]
查看完整版本: 视图中传递重复编写变量如何解决