Cakephp:检查view元素是否存在

时间:2011-03-10 15:36:07

标签: view cakephp-1.3 element

有没有办法检查视图是否存在元素? 我想根据它所属的类别加载不同的元素,但并非所有类别都有一个元素...

3 个答案:

答案 0 :(得分:9)

从CakePHP 2.3版开始,您可以使用View的elementExists方法:

if($this->elementExists($name)) { ... }

在旧版本的2.x中你可以这样做:

if($this->_getElementFilename($name)) { ... }

但遗憾的是在版本1.3中,看起来唯一的方法就是知道完整路径并执行以下操作:

if(file_exists($path . 'elements' . DS . $name . $ext)) { ... }

这就是他们在1.3源代码中所做的事情,但是从各种插件中获取$path并检查每个路径都存在一些复杂性。 (见下面的链接。)

来源:

http://api.cakephp.org/2.3/class-View.html#_elementExists

http://api.cakephp.org/2.0/source-class-View.html#722

http://api.cakephp.org/1.3/source-class-View.html#380

答案 1 :(得分:2)

在控制器中设置元素名称:

$default_element = 'my_element';
$element = 'my_cat_element';

if ($this->theme) {
   $element_path = APP . 'views' . DS . 'themed' . DS . $this->theme . 'elements' . DS . $element . DS . $this-ext;
} else {
   $element_path = APP . 'views' . DS . 'elements' . DS . $element . $this-ext;
}
if (!file_exists($element_path)) {    
   $element = $default_element;
}

答案 2 :(得分:0)

您可以随时通过控制器告知加载特定于“按需”类别的元素。例如:

Within Controller Action:  
$this->set('elementPath', "directory_name/$categoryName");

Within the View (this can also be tried exactly within a Layout):
<?php
if (!empty($elementPath)) { // you can also set a default $elementPath somewhere else, just in case
echo $this->element($elementPath);
}
?>

事实上,甚至还有其他方法可以实现这一目标。如果要在布局中加载元素,则可以从视图本身指定上面显示的set()方法。或者,它甚至可以从url参数中获取,例如:

Within the View or Layout:
<?php
$elementPath = $this->params['url']['category']; // note that the param array can vary according how you set the url; see http://book.cakephp.org/#!/view/963/The-Parameters-Attribute-params
echo $this->element($elementPath);
?>

当然,您将始终必须指定,但同样会检查文件是否存在。

相关问题