【问题标题】:Catch-all route for Twig templatesTwig 模板的包罗万象的路线
【发布时间】:2013-05-19 17:55:07
【问题描述】:

我正在创建一个网站,其中包含多个应用程序(我为每个应用程序创建了一个捆绑包)和一些“半静态”页面。

这个半静态页面是不需要控制器的 Twig 模板,因为它们只包含 HTML 代码,在某些情况下,{% extends %} 使用特定模板,{% if is_granted('ROLE_ADMIN') %} 仅向管理员显示特定内容。

我知道 Symfony 2.1 引入的 FrameworkBundle:Template:template 控制器,但我不能使用这个控制器,因为我不能为设计师创建的每个“静态”页面添加路由。

此外,这些静态页面的 URL 可能有一个或多个子目录(/one、/one/two、/one/two/three...),所以我想出了这个解决方案,如果设计师想要URL 为 mywebsite.com/part1/part2/part3,他会将视图存储在 StaticBundle/Resources/views/part1/part2/part3.html.twig 中,控制器将生成路径 NectStaticBundle:Default:part1/part2/part3。 html.twig

/**
 * @Route("/{part1}")
 * @Route("/{part1}/{part2}")
 * @Route("/{part1}/{part2}/{part3}")
 * @Route("/{part1}/{part2}/{part3}/{part4}")
 * @Route("/{part1}/{part2}/{part3}/{part4}/{part5}")
 */
public function proxyAction($part1='', $part2='', $part3='', $part4='', $part5='') {
    $parameters = func_get_args();
    $parts = array_filter($parameters, 'trim');


    $templatePath = "NectStaticBundle:Default";
    for($i = 0; $i < count($parts) - 1; $i++) {
        if($dir = $parts[$i])
            $templatePath .= "/$dir";
    }
    $name = $parts[$i];
    $templatePath .= "/$name.html.twig";
    $templatePath = preg_replace("/\//", ':', $templatePath, 1);


    $response = $this->container->get('templating')->renderResponse($templatePath);
    return $response;
}

我知道这是一个非常丑陋的 hack,而且很糟糕,所以我想知道是否有人知道更好的方法来实现这一点。

【问题讨论】:

  • 请查看我的回答并评论是否有遗漏/不起作用 - 否则请接受 :)

标签: php symfony twig


【解决方案1】:
/**
 * @Route("/{part1}/{part2}/{part3}/{part4}/{part5}")
 */
 public function proxyAction($part1=null, $part2=null, $part3=null, $part4=null, $part5=null)
 {
      $parts        = array_filter(array($part1, $part2, $part3, $part4, $part5), 'is_null');
      $template     = array_pop($parts);
      $templatePath = 'NectStaticBundle:Default/' .implode("/", $parts) . '/' . $template . '.html.twig'; 

      $response = $this->container->get('templating')->renderResponse($templatePath);
return $response;
  }

没有测试,但无论如何..你明白了:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多