我的问题:我如何允许debug在Silex中使用Twig模板?
我正在玩Silex微框架(一个利用Symfony的PHP框架).
当使用Twig模板系统时,我想输出一个特定的对象.通常情况下,我会var_dump($app);和Twig一起使用{% debug app %}.
我的问题是调试(并设置Silex自己的调试对trueTwig没有帮助)与Silex一起工作.开箱即用的调用debug将导致错误消息:
Twig_Error_Syntax: Unknown tag name "debug" in...
Run Code Online (Sandbox Code Playgroud)
调试调用如下所示:
{% debug app %}
Run Code Online (Sandbox Code Playgroud)
我找到了如何配置Twig的config.yml文件以正确使用的参考,debug但Silex不使用Twig的配置文件.
Silex确实说你可以通过传递一个关联数组来设置选项twig.options,而Twig文档说你可以传递一个环境选项,如:
$twig = new Twig_Environment($loader, array('debug' => true));
Run Code Online (Sandbox Code Playgroud)
试图在Silex中传递它:
$app->register(new Silex\Provider\TwigServiceProvider(), array(
'twig.options' => array('debug' => true),
));
Run Code Online (Sandbox Code Playgroud)
不行.这是错误的选择吗?只是格式不正确?我不知道,我没有尝试过任何作品.
我感觉自己进入了"轮子旋转"模式,所以我在这里问这个问题,希望我能在今天早上继续进行更有成效的工作.:)
(呃......对于超特定的StackOverflow问题,这是怎么回事?)
解决方案:(所有这一切只是为了得到var_dump类似的功能......哦,我的):说实话,这对于屁股来说有点痛苦,而且Silex文档对于发现这一点并没有任何帮助,但这里是我所拥有的要做到这一点.
首先加载Twig自动加载器:
$app['autoloader']->registerPrefixes(array(
'Twig_Extensions_' => array(__DIR__.'/vendor/Twig-extensions/lib')));
Run Code Online (Sandbox Code Playgroud)
你为什么要这样注册?不知道.它是如何实际找到自动加载器的?不知道.但它的确有效.
注册提供程序并设置调试选项:
$app->register(new Silex\Provider\TwigServiceProvider(), array(
'twig.path' => __DIR__.'/views',
'twig.class_path' => __DIR__.'/vendor/Twig/lib',
'twig.options' => array('debug' => true), //<-- this is the key line to getting debug added to the options
));
Run Code Online (Sandbox Code Playgroud)
最后(最好的部分):
$oldTwigConfiguration = isset($app['twig.configure']) ? $app['twig.configure']: function(){};
$app['twig.configure'] = $app->protect(function($twig) use ($oldTwigConfiguration) {
$oldTwigConfiguration($twig);
$twig->addExtension(new Twig_Extensions_Extension_Debug());
});
Run Code Online (Sandbox Code Playgroud)
说实话,我觉得这对我来说足够了Silex.
这个解决方案归功于Nerdpress.
*忍者编辑:一年半之后,我不得不说Silex对我来说是个蠢货.我一直在使用Slim来满足所有微框架需求,这太棒了.快速,干净,简单,轻松地完成工作.
dbr*_*ann 10
我完全删除了旧答案,以显示我构建的一个小示例应用程序的输出:
composer.json:
{
"require": {
"silex/silex": "1.*",
"twig/twig": "1.*",
"twig/extensions": "*"
}
}
Run Code Online (Sandbox Code Playgroud)
app.php:
require_once __DIR__ . '/../vendor/.composer/autoload.php';
$app = new Silex\Application();
$app['debug'] = true;
$app->register(new Silex\Provider\TwigServiceProvider(), array(
'twig.path' => __DIR__ . '/views',
'twig.options' => array('debug' => true)
));
$app['twig']->addExtension(new Twig_Extensions_Extension_Debug());
$app->get('/', function () use ($app) {
return $app['twig']->render('debug_test.twig', array('app' => $app));
});
$app->run();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8474 次 |
| 最近记录: |