我试图使用这个链接将Twig模板实现到代码点火器中,以实现Twig基础知识。
这是我的代码:
require_once(APPPATH.'path/to/Twig/Autoloader.php');
Twig_Autoloader::register();
$loader = new Twig_Loader_Array(array('index' => 'Hello {{ name }}!'));
$twig =new Twig_Environment($loader);
echo $twig->render('index', array('name' =>'Testing Twig'));
它给出输出:
Hello Testing Twig!
但我无法在代码点火器中找到模板文件夹。,
有人能帮我吗?
我所知道的最好、更简单的是:
首先使用composer将trick包含到您的项目中(这将使其保持最新):
composer require "twig/twig:^2.0"
然后,创建包含以下内容的文件application/libraries/Twig.php
(大写很重要):
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
require_once(FCPATH . 'vendor/autoload.php');
class Twig {
private $twig;
public function __construct()
{
$loader = new Twig_Loader_Filesystem(APPPATH . 'views');
$this->twig = new Twig_Environment($loader);
}
public function render($template, $placeholders)
{
return $this->twig->render($template . '.php', $placeholders);
}
}
最后,在这样的控制器中使用它:
public function index()
{
$this->load->library('twig'); // Can also be autoloaded
echo $this->twig->render('some_page_in_views', ['foo' => 'barr']);
}
有人已经制作了用于twitch和ci之间链接的库。
你可以看到下面的链接
https://github.com/bmatschullat/Twig-Codeigniter
有许多项目在CodeIgniter中集成了Twig。
以下是其中的一些(通过CodeIgniter版本):
-
CI 2.x:
- http://edmundask.github.io/codeigniter-twiggy/
- https://github.com/dilantha/codeigniter-twig
-
CI 3.x:
- https://github.com/kenjis/codeigniter-ss-twig
- https://github.com/davidsosavaldes/Attire
这里有一个控制器内部的方法,它用Twig渲染模板。
public function some_method () {
$ci_path = realpath(FCPATH);
Twig_Autoloader::register();
$loader = new Twig_Loader_Filesystem($ci_path.'/application/views');
$twig = new Twig_Environment($loader, array(
'cache' => $ci_path.'/application/views_twig_cache',
));
$template = $twig->loadTemplate('twigtest.php');
echo $template->render(['name'=>'Jhon']);
}
您可能需要做的是将Twig_Loader_Filesystem设置为正确的路径。请注意,我还设置了缓存路径。。。如果您取消设置此项,您的模板将重新生成每个页面加载的速率。
我正在使用composer autoload进行自动加载(请参阅应用程序文件夹中的config/config.php)。我在应用程序/供应商中有composer.json。
希望能有所帮助。