Overriding the Layout for a Joomla View from PHP

A few members of our team at itoctopus are currently working on a highly dynamic eLearning Joomla website that has many components, and each of these component has several views. One of these components was unique in the sense that some of its views had a different layout when the item to be displayed had some specific attributes (all the attributes came from the database). For example, if the category that that item belonged to was “animal”, then the displayed page would have a different layout than that of an item that belonged to a category called “insect”.

In short, here’s what we wanted to accomplish:

  • The client loads the view to display an item in a custom-made component.
  • If the item in question belongs to category XYZ (where XYZ can be the name of any category), then have the view must display the layout for category XYZ.

Doing the above was pretty simple, all we needed to do was to create a file called default_animal.php (we’ll explain, later in this post, the reason why there is default_ in the filename) for example, and place it in the /templates/html/com_componentname/view_name/ directory at the same level of the default.php file and replace the following line (in the view.html.php file):


With this code:

//we are assuming that $categoryName exists
if (!empty($categoryName)){

$categoryName in our code above is the name of the category, for example fish. Note that if the file default_[categoryName] does not exist, then the above code will not work, and you will see the following error when you load the view:

500 – Layout default_[categoryName] not found

So, there you have it – now you know how to load a layout dynamically from a view.

But why do we need the default_ prefix in our filename?

Is it because the function loadTemplate which is called by function display and which is located in the file view.php (which, in its turn, is located in the /libraries/joomla/application/component/ directory) has the following code:

if ($this->_template == false)
	$filetofind = $this->_createFileName('', array('name' => 'default' . (isset($tpl) ? '_' . $tpl : $tpl)));
	$this->_template = JPath::find($this->_path['template'], $filetofind);

As you can see from the above, the function explicitly adds ‘default’ to the name of the layout (in case the name of the layout is NULL, then the function will simply try to load default.php).

Now if you need help building your views on your custom Joomla components, or you need help on anything Joomla, then you’re at the right place. Just contact us and we’re confident that you’ll be impressed with our speed, efficiency, and professionalism – not to mention our very affordable prices!

No comments yet.

Leave a comment