What not to do in a template

The Achilles' heel of eZ Publish is the template system subframework that cannot, and should not, be overrated, and that is used as a true programming language.

For this reason, we should not have templates with very complex logic. The templates should only render HTML data, and not involve any kind of business logic.

If the predefined objects of eZ Publish that we can use in our templates are not sufficient to publish the data that we want to represent, we should move the business logic either inside an operator or function, or create a new module.

A classic error that many developers make is to perform many queries in a single template file. It is not recommended to have more than two queries within the same template. If we need more than two queries we have to use a template operator or a custom fetch function, which are much faster to execute.

For example, if we have to print the children of a node, we should use the $node.children attribute, rather than making a new query that returns childrens.

The following code should not be used:

{$childrens=fetch(content, list, hash(parent_node_id, $node.node_id))}
{foreach $childrens as $children}
{node_view_gui view=line content_node=$children}
{/foreach}

This must be replaced with the following:

{foreach $node.children as $children}
{node_view_gui view=line content_node=$children}
{/foreach}

In this way, we optimize the template performance because we don't use the fetch function in the template, but the children attribute of the node, which decreases the query's number.

Another trick is to limit and page the template queries, to reduce the database load:

{fetch( 'content', 'list', hash('parent_node_id', 2, 'limit', 15, 'offset', 10) )}

The content list fetch function takes two parameters: limit and offset. The limit parameter sets the item number to be listed, whereas the offset parameter sets the first element from where the query starts.

In conclusion, wrong templates are those where:

  • Business logic is created through the template language instead of through PHP code
  • There are more than two template queries
  • There are template queries that can be replaced by ready-made attributes of the node object
  • Template queries are not limited and not paginated
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.71.21