在 Silex 中,我可以使用 Twig 模板,但我想使用 Twig 的 PHP 引擎,而不是 Twig 语法。例如本指南 http://symfony.com/doc/current/cookbook/templating/PHP.html描述了如何为 Symfony 而非 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',
));
});
My 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
,因此我知道这不是 Web 服务器或 PHP 配置问题。
如果您想在 Silex 中模仿此行为,则需要通过 Composer 安装 TwigBridge。然后构建templating
服务方式与 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"
},
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)