我在Symfony中使用了Twig,我真的很喜欢它。我现在有一个CodeIgniter项目,我想将Twig与它集成。
我通过Composer安装了CodeIgniter和Twig的最新版本,并遵循了本教程,但我相信教程中的代码适用于CI v3。
任何将Twig与CI v4集成在一起的人都能帮助我获得正确的代码吗。
更新
下面的解决方案!
试试这个,我希望它能帮助你
安装Composer并运行以下命令以获得最新版本:
composer require "twig/twig:*"
安装后,将这行代码添加到config文件夹中的Services.php文件中,即app => Config => Services.php
,就像下面的代码一样
....
public static function twig($viewDir = null, $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('twig', $viewDir);
}
$appPaths = new ConfigPaths();
$appViewPaths = $viewDir ?? $appPaths->viewDirectory;
$loader = new TwigLoaderFilesystemLoader($appViewPaths);
return new TwigEnvironment($loader, [
'cache' => WRITEPATH.'/cache/twig',
]);
}
....
**然后在你的控制器中调用你刚刚创建的服务方法,就像这个
namespace AppControllers;
use CodeIgniterController;
use CodeIgniterHTTPRequestInterface;
use CodeIgniterHTTPResponseInterface;
use PsrLogLoggerInterface;
use ConfigServices; // Add the services namespace
class BaseController extends Controller
{
protected $helpers = [];
protected $twig;
// protected $helper = [];
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
$this->twig = Services::twig(); // call the twig service you just created
}
}
因此,现在您可以调用其他控制器中的视图文件扩展到父控制器BaseController例如
namespace AppControllers;
class Home extends BaseController
{
public function index ()
{
// To load a template from a Twig environment, call the load() method which returns a TwigTemplateWrapper instance:
$template = $this->twig->load('index.html');
// To render the template with some variables, call the render() method:
return $template->render(['the' => 'variables', 'go' => 'here']);
// The display() method is a shortcut to output the rendered template.
// OR You can also load and render the template in one fell swoop:
return $this->twig->render('index.html', ['the' => 'variables', 'go' => 'here']);
// If a template defines blocks, they can be rendered individually via the renderBlock() call:
return $template->renderBlock('block_name', ['the' => 'variables', 'go' => 'here']);
// Note any of them above will work
}
}
如果你仍然想使用view()
和类似树枝的codeigniter 4默认视图功能,你可以修改应用程序目录中的Common.php
文件通过在下面添加此代码块。
if (!function_exists('view'))
{
function view($tpl, $data = []) {
$twig = ConfigServices::twig(); // call the twig service you just created
return $twig->render($tpl, $data);
}
}
然后在控制器中像这样调用
return view('index', ['name' => 'Chibueze Agwu'])
然后在视图文件index.twig
中
<!DOCTYPE html>
<html>
<head>
<title>My Webpage</title>
</head>
<body>
<h1>My Webpage</h1>
{{ name }}
</body>
</html>
这将输出
我的网页
Chibueze Agwu
我还没有测试这个代码,但我希望它能工作。如果没有,请引起我的注意。为了遵守DRY
(DO NOT REPEAT YOURSELF
(的规则,你可以继续改进代码,我稍后会这样做
我前段时间找到了解决方案,我会把它发布出来,以防有人偶然发现这个问题。
-
首先,所有控制器都必须扩展
BaseController
;此控制器在安装CodeIgniter 4时默认可用。 -
创建一个自定义助手文件并放入
[project-name]/appstarter/app/Helpers
。
重要
- 助手的名称必须是
[name]_helper.php
,否则将无法工作
例如,矿井被称为custom_helper.php
-
在您刚刚创建的自定义帮助程序中创建以下函数:
use TwigEnvironment; use TwigExtensionDebugExtension; use TwigLoaderFilesystemLoader; use TwigTwigFilter; if (!function_exists('twig_conf')) { function twig_conf() { // the follwing line of code is the only one needed to make Twig work // the lines of code that follow are optional $loader = new FilesystemLoader('Views', '../app/'); // to be able to use the 'dump' function in twig files $twig = new Environment($loader, ['debug' => true]); $twig->addExtension(new DebugExtension()); // twig lets you create custom filters $filter = new TwigFilter('_base_url', function ($asset) { return base_url() . '/' . $asset; }); $twig->addFilter($filter); return $twig; } }
注意
- 在创建任何自定义过滤器之前,请确保Twig还没有内置过滤器
-
现在在
BaseController
中,您会发现一个名为$helpers
的空数组。你必须把你的自定义助手的名字放在里面。我的名字叫custom_helper.php
;所以代码对我来说是这样的:protected $helpers = ['custom'];
-
就在数组下面,你会发现
BaseController
的构造函数,这就是Twig库初始化的地方;通过调用您在自定义助手中创建的函数:public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger) { parent::initController($request, $response, $logger); $this->twig = twig_conf(); }
-
现在你可以出发了!要在任何控制器中渲染你的树枝文件:
return $this->twig->render('twig_name', $dataArray);
试试这个吧,我希望它能对你有所帮助。
安装Composer并运行以下命令以获得最新版本:
composer需要"树枝/树枝:^3.0";