2011-03-10 80 views

回答

9

由於CakePHP的2.3,你可以使用視圖的elementExists方法版本:

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

在舊版本2.x的,你可以這樣做:

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

但可悲的是1.3版本中,它看起來像唯一的辦法是知道完整的路徑,並做類似的事情:

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

T帽子是他們在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

+0

我試圖從控制器調用此但不工作的版本2.4 – 2015-07-01 11:32:29

+1

@MohamadAli'elementExists() '是一個View方法,所以不應該從控制器調用。 – drmonkeyninja 2015-07-02 11:47:20

+0

@drmonkeyninja我需要檢查渲染視圖之前如何從控制器檢查它?目前我使用try/catch – 2015-07-03 14:02:46

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; 
} 
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); 
?> 

當然,你總是必須指定,但同樣會去的,如果該文件存在檢查。