【问题标题】:Cakephp : check template file exist or not?Cakephp:检查模板文件是否存在?
【发布时间】:2015-07-03 16:58:36
【问题描述】:

在Cakephp 2.4 版本的控制器中,在渲染视图之前需要检查视图文件是否存在?然后决定渲染。例如我需要一些类似下面的代码。

if( template_exist( $template_name ) )
{ 
   $this->render( $template_name );
}
else
{
   $this->render( $default_template );
}

目前我使用 try/catch,但我寻求最好的方法。我需要函数 template_exist 有人可以帮忙吗?

【问题讨论】:

    标签: cakephp


    【解决方案1】:

    您可以通过创建一个新的 View 对象然后使用 elementExists() 检查模板是否存在来从控制器执行此操作:-

    $View = new View($this, false);
    if ($View->elementExists($templateName) === true) {
        $this->render($templateName);
    } else {
        $this->render($defaultTemplate);
    }
    

    这样,Cake 会检查元素模板的所有常用位置。

    【讨论】:

    • 感谢您花时间回答,但它不工作它总是返回 false 无论模板文件是否存在我在直接文件和子目录上测试过
    • 你传递的$templateName是什么?它不应包含 .ctp 扩展名。看看elementExists() 调用的View::_getElementFilename() 方法。你会看到它使用file_exists() 来检查文件。您要么错误地传递了视图文件,要么该文件不存在。当你调用它的一个方法时,总是值得看看 Cake 实际在做什么,因为它通常会揭示你的问题的原因。 :-)
    • 我通过了 $this->render( $templateName ) 可以更红的东西。这对我来说很奇怪
    • 我会尝试调试 View:: _getElementFilename() 以查看它在哪里失败,因为这应该可以工作。也许有一个错误。
    • 这不起作用,因为它专门在元素文件夹if (file_exists($path . 'Elements' . DS . $name . $ext)) {中寻找模板文件
    猜你喜欢
    • 1970-01-01
    • 2011-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-01
    • 2012-08-13
    • 2018-06-08
    相关资源
    最近更新 更多