In this section, we focus on Layouts and Blocks in View.
Unlike other mainstream PHPMVC architectures, magento's ActionController does not pass data objects to the view, nor does it set properties in the View object. View obtains the information it needs through system modules.
The result of this design is that View is divided into Blocks and Templates. Blocks are PHP objects, and Templates are a mixture of PHP code and HTML (it can also be considered that PHP is used as a template language). Each Block is bound to a Template file. In a Phtml file, the PHP keyword $this will contain a reference to the Block corresponding to the Template.
Here is a quick example. View the template file app/design/frontend/base/default/template/catalog/product/list.phtml
You will see the following code
getLoadedProductCollection() ?>
count()): ?>
__("There are no products matching the selection.")?>
The getLoadedProudctController can be found in the corresponding block file
app/code/core/Mage/Catalog/Block/Product/List.php
public functiongetLoadedProductCollection()
{
return$this->_getProductCollection();
}
The _getProductCollection will instantiate models and get the data to the corresponding template.
Embedded Block
The real power of Blocks/Templates is the getChildHtml method. This allows us to include the secondary Block/Template in the main Block/Template (in xml format)
Blocks calling Blocks will form our entire HTMLlayout. Look at an example
App/design/frotend/base/default/template/page/1column.phtml
< htmlxmlns="http://www.w3.org/1999/xhtml" xml:lang="?php echo$this->getLang() ?>" lang=" getLang()?>"> getChildHtml('head') ?>
getChildHtml('content') ?> getChildHtml('before_body_end') ?>
getAbsoluteFooter() ?>
The file is not long, but each call is $this->getChildHtml(…), which will include and render other blocks. These blocks may also call other blocks.
Layout
Although Block and Template are good, you may have the following questions
1. How do I tell Magento which Block is used in the page?
2. How do we tell Magento it is initial
3. How do I tell each Block to call the following block
At this time, the Layout object is needed. The Layout object is in Xml format and defines which Blocks are included in a page and which Blocks are responsible for rendering the page.
We did the previous Hello World project directly on Action Method. This time we create a simple HTMLtemplate to serve the module.
First create a file
App/design/frontend/base/default/layout/local.xml
Then write the following content
Then create another file
app/design/frontend/base/default/template/simple_page.phtml (note that it is consistent with the template in the configuration)
Write the following content
Untitled
body { background-color:#f00; }