php - 如何在此 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。我有:
添加了简单安全的 Twig库
application\libraries\Twig.php
:在
third_party
目录中,我添加了 Twig 本身。在
application\config\autoload.php
我加载了twing:$autoload['libraries'] = array('database', 'form_validation', 'session', 'user_agent', 'twig');
在以下位置设置 Twig 视图的路径
application\libraries\Twig.php
:
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>
我究竟做错了什么?
解决方案
推荐阅读
- python - 如何在火花python中过滤删除空值
- r - 用 R 将一个向量的元素分配给另一个向量的元素
- angular - 猫头鹰日期时间选择器角度时间验证
- cassandra - 如果在 gc.grace.seconds 期间没有读取该数据,Cassandra 是否会在没有手动修复的情况下达到最终一致性?
- sql-server - 无法浏览托管在分析服务器上的多维多维数据集
- python - 选定列的唯一值转换为数据框列
- c# - 如何在 SSRS Express 中生成 HTML 报告并通过电子邮件发送
- c - 有人可以帮我下面的函数返回垃圾字符吗
- r - 如何在R中找出索引
- oracle - 求解析函数的 Row_Number() 的 MIX 和 MAX?