首页 > 解决方案 > 如何在此 Codeigniter 3 应用程序中将变量传递给 Twig 视图?

问题描述

我正在使用CodeIgniter 3.1.8和 Bootstrap 4开发在线报纸/博客应用程序。我决定为其添加主题。该应用程序不是 HMVC,只有 MVC。

主题目录位于应用程序之外,如下图所示:

在此处输入图像描述

主题内,我有包含“主视图”的主题目录(当然)layout.php

在此处输入图像描述

我如何使用主题视图

application/core我添加了一个MY_Loader.php包含以下内容的文件:

<?php defined('BASEPATH') OR exit('No direct script access allowed');

  class MY_Loader extends CI_Loader {

    function theme_view($folder, $view, $vars = array(), $return = FALSE) {
      $this->_ci_view_paths = array_merge($this->_ci_view_paths, array(FCPATH . $folder . '/' => TRUE));
      return $this->_ci_load(array(
              '_ci_view' => $view,
              '_ci_vars' => $this->_ci_prepare_view_vars($vars),
              '_ci_return' => $return
          ));
    }

}

在我的 Posts 控制器的index()方法中,我加载视图并传递数据:

public function index() {
   //more code here
   $data['posts'] = $this->Posts_model->get_posts($config['limit'], $config['offset']);
   $this->load->theme_view('/themes/caminar/', 'layout', $data);
}

使用 Twig 作为主题

尽管我没有 Symfony 知识,但我认为将Twig模板引擎用于主题是一个好主意。

为此,我使用CodeIgniter Simple and Secure Twig。我有:

private $config = [ 'paths' => [FCPATH . '/themes', VIEWPATH], 'cache' => '/path/to/twig/cache', ];

问题

根据CodeIgniter Simple and Secure Twig的文档,我们可以像这样设置一个全局变量:$this->twig->addGlobal('sitename', 'My Awesome Site');

所以,我$this->twig->addGlobal('siteTitle', 'My Awesome Site');在 Posts 控制器中添加了:

public function index() {

  //call initialization method
  $config = $this->_initPagination("/", $this->Posts_model->get_num_rows());

  $data = $this->Static_model->get_static_data();
  $data['pages'] = $this->Pages_model->get_pages();
  $data['categories'] = $this->Categories_model->get_categories();  

    //use limit and offset returned by _initPaginator method
  $data['posts'] = $this->Posts_model->get_posts($config['limit'], $config['offset']);
  $this->twig->addGlobal('siteTitle', 'My Awesome Site');
  $this->load->theme_view('/themes/caminar/', 'layout', $data);
}

然而,在标签内没有显示“My Awesome Site”的themes\caminar\layout.php行。<title>{{siteTitle}}</title><title>

我究竟做错了什么?

标签: phpcodeignitersymfonytwigcodeigniter-3

解决方案


推荐阅读