How to use Joomla! JLayouts in your extensions

joomla-jlayout

With JLayouts you can create content elements that you can use in multiple Joomla Views. For example for sharing content between the frontend and backend, or between a component and a module. You can even share them between different extensions. 

In opposite to the view they are not included in the JView(Legacy) and you can't use the context of it ($this). Instead you need to prepare an array of data you want to hand over it to the layout.

<?php
// ...
// Get the layout file
$layout = new JLayoutFile('sample',  $basePath = JPATH_ROOT
    . '/administrator/components/com_mycomponent/layouts');

// Display it
echo $layout->render(array('Mr.', 'Martin')); 

As you can see we we first have to load a Joomla JLayout file called sample (Joomla is now looking for a file called sample.php) and also added the path to it.

After this we call the JLayoutFile render methods, which than renders the file with the given data we echo. You can just include one parameter, so you have to use arrays or an object if you want to handover multiple values.

In the JLayout file we get our parameters in a variable named $displayData. 

<?php
// ...
list($title, $name) = $displayData;

echo $title . ' ' . $name; 

As you can see our Array is available in the $displayData array and we use list to assign it to variablesocoursyocoulalsuse $displayData[0] etc.

By the way, be careful with list - the behavior changed in PHP 7! Now the variables are attached from the left instead from right, as in previous PHP versions, when you have complex arrays that can change the indexes!

One of the other advantages of Joomla JLayout files is also that they can be overriden in templates! And you can load sub layouts in JLayouts, so keep them as small as possible! (sample, sample.greeting, sample.text)

Rate this blog entry:
1
CForms 2.0 released
Which Frontend CSS Framework for Joomla 3.7 should...