2014-03-07 45 views
6

在Silex中,我能夠使用Twig模板,但我想使用Twig的PHP引擎而不是Twig語法。例如this guide描述瞭如何爲Symfony而不是Silex做到這一點。如何在Twig中使用PHP模板引擎代替Silex中的Twig語法

我的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; ?>這不是招沒有執行。

我懷疑可能有一個小枝配置設置來告訴它我想使用PHP樣式模板。爲了澄清,如果我用樹枝代替語法,例如: -

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

然後它的作品,我看到名字Bob,所以我知道這是不是一個Web服務器或PHP配置問題。

回答

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" 
}, 
+0

我已經更新了我與工作解決方案的答案實現這一目標。 –

+0

+1感謝您的詳細解答。是否可以手動複製必要的文件而不是使用Composer? – ServerBloke

+0

@ServerBloke np,作曲家會爲你做。我已經在你的composer.json中添加了你需要的答案。 –