在视图文件中扩展代码点火器中的自定义配置数组


Extending custom config array in Codeigniter within a view file

我正在使用codeigniter 2.x。我需要的是从视图文件/views/home.php内部将值插入到config/template.php数组中。

我创建了一个自定义配置文件application/config/template.php

$config['site_name'] = "Sitename";
$config['site_lang'] = "En-en";
$config['page_name'] = "Pagename";
$config['css_page'] = "default";
$config['alias'] = "";
$config['head_meta'] = array(
    'description' => 'description',
    'keywords' => 'meta, keywords',
    'stylesheets' => array(
        'template.css'
    ),
    'scripts' => array(
        'jquery.js',
        'template.js'
    ),
    'charset' => 'UTF-8'
);
$config['sidebars'] = array();

然后,我使用 application/views/template/template.php 作为我的主要 HTML 布局,一开始我包含一个文件application/views/template/includes/inc-tpl-cfg.php,它将我的模板配置全球化为一个带有数组的文件,这样我就可以更轻松地访问它们。以下是该inc-tpl-cfg.php的内容:

<?php
// No direct acces to this file
if (!defined('BASEPATH')) exit('No direct script access allowed');
/* Template configuration needs to be defined to make them accessible in the whole template */
$cfg_template = array(
    'sitename'      => $this->config->item('site_name'),
    'sitelang'      => $this->config->item('site_lang'),
    'pagename'      => $this->config->item('page_name'),
    'csspage'       => $this->config->item('css_page'),
    'charset'       => $this->config->item('charset','head_meta'),
    'description'   => $this->config->item('description','head_meta'),
    'keywords'      => $this->config->item('keywords','head_meta'),
    'stylesheets'   => $this->config->item('stylesheets','head_meta'),
    'scripts'       => $this->config->item('scripts','head_meta'),
    'sidebars'      => $this->config->item('sidebars')
);
/* Template variables */
$cfg_assetsUrl = base_url() . 'assets';
// If pagename exists than concatenate it with a sitename, else output only sitename
if(!empty($cfg_template['pagename'])){
    $title = $cfg_template['pagename'] . ' - ' . $cfg_template['sitename'];
}else{
    $title = $cfg_template['sitename'];
}

我的主要模板布局中有一部分是带有侧边栏的块:

<div id="tpl-sidebar">
  <?php foreach($cfg_template['sidebars'] as $sidebar):?>
    <?php $this->load->view('modules/'. $sidebar);?>
  <?php endforeach ;?>
</div>

最后,它将application/views/home.php加载到applications/views/template/template.php内部的特定div块中。这是一个/views/home.php

<?php
// No direct acces to this file
if (!defined('BASEPATH')) exit('No direct script access allowed');
// Page configuration
$this->config->set_item('page_name','Homepage');
$this->config->set_item('css_page','home');
$this->config->set_item('alias','home');
?>
    <p>
        WELCOME BLABLABLA
    </p>
</h3>

在一节中,我可以定义/覆盖config/template.php的默认值,并为每个视图使用特定的默认值。所以我的问题是,如何通过插入一些新项目来扩展此视图文件中的$config[sidebar]数组,例如:recent.phprss.php等......?

对不起,代码很大。

提前谢谢。

为什么不在控制器中设置配置变量? 视图不适用于逻辑。

您不应该在视图中执行此操作,设置数据应从控制器完成。视图应该只处理视图逻辑,而不是设置逻辑本身...然后,当一切就绪并准备就绪时,将变量从控制器传递到视图中。

好的,我明白了:

这是我应该在views/home.php中插入的内容:

$this->config->set_item('sidebars',array(
  'recent',
  'rss'
));

无论如何,谢谢。