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

Ser*_*oke 6 php symfony twig silex

在Silex中,我可以使用Twig模板,但我想使用Twig的PHP引擎,而不是Twig语法.例如,本指南介绍了如何为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',
    ));
});
Run Code Online (Sandbox Code Playgroud)

index.html.php看起来像:

<p>Welcome to the index <?php echo $view->name; ?></p>
Run Code Online (Sandbox Code Playgroud)

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

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

<p>Welcome to the index {{ name }} </p>
Run Code Online (Sandbox Code Playgroud)

然后它工作,我看到名称Bob,因此我知道这不是一个Web服务器或PHP配置问题.

Ada*_*ney 7

如果要在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();
Run Code Online (Sandbox Code Playgroud)

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

"require": {
    "silex/silex": "~1.0",
    "symfony/twig-bridge": "~2.0",
    "symfony/templating": "~2.0",
    "twig/twig": "~1.0"
},
Run Code Online (Sandbox Code Playgroud)