CakePHP: check if view element exists

Is there a way to check if an item exists for a view? I want to load another element according to the category to which it belongs, but not for all categories there is an element for it ...

+7
source share
3 answers

In CakePHP version 2.3, you can use the View elementExists method:

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

In older 2.x versions, you can:

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

But, unfortunately, in version 1.3 this is the only way to find out the full path and do something like:

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

This is what they do in source code 1.3, but there is some difficulty in getting $path from various plugins and checking each of these paths. (See link below.)

Sources:

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

+9
source

set element name in controller:

 $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
source

You can always download an item in the on-demand category by reporting this from the controller. For example:

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

In fact, there are other ways to achieve this. If the element is loaded into the layout, the set () method shown above can be specified from the view itself. Or you can even extract it from url parameters, for example:

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

Of course, you always need to specify, but the same thing would be to check if the file exists.

0
source

All Articles