簡體   English   中英

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

[英]How to use the PHP template engine in Twig instead of the Twig syntax within 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',
    ));
});

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

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

當我在瀏覽器中運行應用程序並查看源代碼時,我看到文字字符串<?php echo $view->name; ?> <?php echo $view->name; ?>尚未執行。

我懷疑可能有一個Twig配置設置告訴它我想使用PHP樣式模板。 為了澄清,如果我使用Twig語法,例如:

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

然后它工作,我看到名稱Bob ,因此我知道這不是一個Web服務器或PHP配置問題。

如果要在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"
},

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM