如何检查 test.html.twig 是否存在?

时间:2021-01-17 10:30:43

标签: php symfony controller twig symfony5

我在 Symfony 5 中创建了一个控制器:

/**
 * @Route ("/{slag}", name="test")
 */
public function index($slag): Response
{
    $test = $slag . '.html.twig';
    return $this->render($test, [
        'title' => 'TEST'
    ]);
}

然后创建模板 test1.html.twigtest2.html.twigtest3.html.twig

当转到地址 http://localhost/test1 时,显示 test1.html.twig 和 ... .

但是当转到地址 http://localhost/test4 时,重定向到 http://localhost/

我将它用于登录页面,不需要对数据库进行很多请求。

1 个答案:

答案 0 :(得分:1)

你可以使用 try/catch。

public function index($slag): Response
{
    $test = $slag . '.html.twig';
    try {
        return $this->render($test, [
            'title' => 'TEST'
        ]);
    } catch (\Exception $e) {
        return $this->redirectToRoute('index');
    }
}
相关问题