Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

There are differences between view blocks or elements in cakephp?

Tags:

cakephp

have any difference using view blocks or elements for a simple navigation bar, or a dynamic menu with mysql content(with requestAction() method)? Which is more appropriate?

like image 311
Marcelo Aymone Avatar asked Jan 10 '23 10:01

Marcelo Aymone


1 Answers

Yes, there is a difference. Elements are just pieces of php/HTML you write in a separate .ctp file that will get inserted where you call $this->element().

Blocks are harder to explain. Blocks are areas of the view that you can define elsewhere. Blocks can even contain elements. The best example to explain blocks I can think of is in the standard CakePHP layout, there are lines in the header

echo $this->fetch('meta');
echo $this->fetch('css');
echo $this->fetch('script');

These are lines saying to render the blocks "meta", "css", and "script" in this spot. You can edit the meta, css, script blocks in your views, even after $this->fetch(); for the respective block is called. For example, I've used the following all the time:

echo $this->Html->script('javascript', array('block' => 'script')); 

This will add the javascript includes into the script block, and I can use it in the view files, in an element, wherever. So, I use this trick to have which javascript files are included based on which view.ctp file you're looking at.

I should note the way script, css, and meta blocks end up getting defined is different from how you normally define blocks. The way you normal define a block's contents is like this:

$this->start('block');
//Block contents here
$this->end();

When should I use elements vs blocks?

In most cases, elements are going to be good enough. You could probably even accomplish pretty much anything without using blocks, though if you get how to use them, they can be convenient, or lead to better design.

With blocks, look for cases where you know you want to reuse some piece of the view, but the piece has some variation based on something that cannot be determined yet.

Pieces of layouts are a common example. Perhaps you want to display the name of the page in the layout. You could set the $name variable in your controllers' actions. But there's a possibility that later you might want to retheme the site later on, and then you no longer want to display page names in the new theme. Then you should remove the line that sets the $name variable from your controllers, to be clean. Or, you could avoid this problem by using blocks, and defining the page name that should be displayed in the view.ctp files themselves. Now your application is more MVC.

Read more about elements and blocks in the official cookbook: http://book.cakephp.org/2.0/en/views.html

like image 119
Kai Avatar answered May 11 '23 01:05

Kai