How to Create and Customize Template Files in Magento 1.x and 2.x

How to Create and Customize Template Files in Magento 1.x and 2.x

What are the conventions for variable naming?

When naming classes and methods, it is taken to use the standard called “CamelCase”. According to the standard, each word in the middle of the phrase should begin with a capital letter. Besides, any separator, for example, underscore is not allowed to use.

If you’d like to get your code more readable, you should follow the next rules:

  • Local or “private” variables and methods are prefixed with underscore: $_loacalVar , $_cartHelper, _prepareLayout;
  • Class name always begins with a capital letter: Breadcrumbs, AbstractItem, Card;
  • Methods that return logic values (true or false) are prefixed with “is”: isContentMode, isProductMode;
  • Methods that check content are prefixed with “has”: hasProductUrl, hasError;
  • Methods that return any value are prefixed with “get<Return_type>”: getProduct, getChildHtml;
  • Methods that perform conversion to a type are prefixed with “to”: toHtml, toOptionArray.

The rules mentioned above are used both in Magento 1.x and 2.x. There are no differences at all.

What does $this refer to in template files?

In fact, $this refers to the parent PHP block object where the template has been declared. There are some changes that have been applied in Magento 2.x. If you’d like modules and themes to pass validation magento 2 coding-standard, it is recommended to use $block instead of $this, which in turn refers to $this->_currentBlock.

Example:

How can another template be included inside the current one?

The only thing you should do is to declare a descendant block in a parent block by determining attributes: type, name, as, template, after, before.

Note: the attributes “after” and “before” (for block positioning) will work only while calling method “getChildHtml” without parameters!

Then, it’s necessary to determine a descendant block for a parent template:

Moreover, it is possible to call descendant template output in any necessary place of a parent template. You should call getChildHtml method and pass the name of the descendant block as the first parameter.



1 comment

Post a new comment

top