gpt4 book ai didi

php - Symfony2 -> 如果请求的格式(例如移动)不存在,则渲染默认格式(例如 html)

转载 作者:搜寻专家 更新时间:2023-10-31 20:46:30 25 4
gpt4 key购买 nike

在 Symfony2 中,当尝试呈现 index.mobile.twig 时,index.mobile 时,我将如何加载 index.html.twig。 twig 不存在。 而不是获取“此模板不存在错误”。

我相信答案在于为 Twig 创建自定义加载器,但我找不到任何关于它的文档,只是偶尔引用它。

最佳答案

答案涉及扩展 twig.loader.class 并在发现特定的 twig 模板不存在并且在抛出异常之前创建一个额外的步骤。

第 1 部分 - 配置

答案涉及扩展 twig.loader.class

  1. 创建一个扩展 Twig FilesystemLoader 文件的 customloader.php

    namespace Acme\MyBundle\Twig\Loader;       
    use Symfony\Bundle\TwigBundle\Loader\FilesystemLoader;
    class CustomLoader extends FilesystemLoader{}
  2. 修改您的 config.yml 以包括:

 parameters:      twig.loader.class: Acme\YourBundle\Twig\Loader\name_of_your_class

PART 2 - Extending the class

Extending the class is fairly straight forward.. The method I needed to modify was findTemplate($template). It's very small method and you could probably use parent:: to extend the original code more properly.. However, I chose to completely over-write it and include the following code right before the Unable to find template error:

    if (false === $file || null === $file) {

switch( $template->get('format')){
case 'mobile':
$template->set('format','html');
return self::findTemplate($template->getLogicalName());
break;
}

throw new \Twig_Error_Loader(sprintf('Unable to find template "%s".', $logicalName), -1, null, $previous);

代码发现文件存在后,会检查 mobile 是否为请求的格式。如果是,它将模板对象的格式设置为 html,然后尝试 name.html.twig。在这方面您还可以做很多事情,但这解决了我的问题。

关于php - Symfony2 -> 如果请求的格式(例如移动)不存在,则渲染默认格式(例如 html),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12521243/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com