gpt4 book ai didi

php - 如何在 Twig 中使用 PHP 模板引擎而不是 Silex 中的 Twig 语法

转载 作者:可可西里 更新时间:2023-11-01 13:19:25 25 4
gpt4 key购买 nike

在 Silex 中,我可以使用 Twig 模板,但我想使用 Twig 的 PHP 引擎,而不是 Twig 语法。例如this guide描述了如何为 Symfony 而不是 Silex 做到这一点。

我的 Silex index.php看起来像:

$app->register(new Silex\Provider\TwigServiceProvider(), array(
'twig.path' => __DIR__.'/views',
));

$app->get('/', function() use ($app) {
return $app['twig']->render('index.html.php', array(
'name' => 'Bob',
));
});

我的 index.html.php看起来像:

<p>Welcome to the index <?php echo $view->name; ?></p>

当我在浏览器中运行应用程序并查看源代码时,我看到了文字字符串 <?php echo $view->name; ?>尚未执行。

我怀疑可能有一个 Twig 配置设置告诉它我想使用 PHP 样式模板。澄清一下,如果我改用 Twig 语法,例如:

<p>Welcome to the index {{ name }} </p>

然后它工作了,我看到了名字 Bob ,因此我知道这不是网络服务器或 PHP 配置问题。

最佳答案

如果您想在 Silex 中模仿这种行为,您需要通过 Composer 安装 TwigBridge。然后像 Symfony 一样构建模板服务。

此解决方案有效,因为我已成功测试它。

<?php

require __DIR__.'/vendor/autoload.php';

use Silex\Application;
use Symfony\Component\Templating\PhpEngine;
use Symfony\Component\Templating\TemplateNameParser;
use Symfony\Component\Templating\Loader\FilesystemLoader;
use Symfony\Component\Templating\DelegatingEngine;
use Symfony\Bridge\Twig\TwigEngine;

$app = new Application();

$app['debug'] = true;

// Register Twig

$app->register(new Silex\Provider\TwigServiceProvider(), array(
'twig.path' => __DIR__.'/views',
));


// Build the templating service

$app['templating.engines'] = $app->share(function() {
return array(
'twig',
'php'
);
});

$app['templating.loader'] = $app->share(function() {
return new FilesystemLoader(__DIR__.'/views/%name%');
});

$app['templating.template_name_parser'] = $app->share(function() {
return new TemplateNameParser();
});

$app['templating.engine.php'] = $app->share(function() use ($app) {
return new PhpEngine($app['templating.template_name_parser'], $app['templating.loader']);
});

$app['templating.engine.twig'] = $app->share(function() use ($app) {
return new TwigEngine($app['twig'], $app['templating.template_name_parser']);
});

$app['templating'] = $app->share(function() use ($app) {
$engines = array();

foreach ($app['templating.engines'] as $i => $engine) {
if (is_string($engine)) {
$engines[$i] = $app[sprintf('templating.engine.%s', $engine)];
}
}

return new DelegatingEngine($engines);
});


// Render controllers

$app->get('/', function () use ($app) {
return $app['templating']->render('hello.html.twig', array('name' => 'Fabien'));
});

$app->get('/hello/{name}', function ($name) use ($app) {
return $app['templating']->render('hello.html.php', array('name' => $name));
});

$app->run();

您至少需要这些依赖项才能在您的 composer.json 中实现此目的

"require": {
"silex/silex": "~1.0",
"symfony/twig-bridge": "~2.0",
"symfony/templating": "~2.0",
"twig/twig": "~1.0"
},

关于php - 如何在 Twig 中使用 PHP 模板引擎而不是 Silex 中的 Twig 语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22246104/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com