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

时间:2014-03-07 09:23:59

标签: php symfony twig silex

在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,因此我知道这不是Web服务器或PHP配置问题。

1 个答案:

答案 0 :(得分:7)

如果您想在Silex中模仿此行为,则需要通过Composer安装TwigBridge。然后以与Symfony相同的方式构建templating服务。

此解决方案可以正常运行,因为我已经成功测试了它。

<?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"
},