Work In Progress

This book is currently work in progress. Some sections are not yet written. Thank you for your understanding!

View Templates

I know what you're thinking: “what's the fox doing in the country fair?”, er, ”what are view templates doing in a plugin?”. And yet, they do make sense in some use cases. Core Joomla! uses them for the voting, page navigation, and page break content plugins, for the WebAuthn Multi-factor Authentication plugin (which needs to render its own, different interface to the regular code entry interface of most MFA plugins), as well as all custom fields plugins.

And now you probably went “a-ha!”. Yes, plugins need to have view templates when they are supposed to emit precomposed HTML, usually to be injected into some content.

Back in the olden days (Joomla! 1.x and 2.x) there was no such thing. HTML generation was taking place in the code which, as I hope you understand by reading this book, is a Very Bad Thing. As to why it is such a bad thing, ask any site integrator who cut their teeth on Joomla! 1.x and 2.5. They will tell you that trying to coax that output to display the way they needed to was a royal pain in the posterior, if at all possible. Having view templates in plugins means they can be overridden, ergo you have separated the business logic of your plugin from the presentation of its results, making both the developer (that's you!) and the site integrator happy.

View templates for plugins are always stored in the tmpl folder of the plugin.

Using a view template is a two step process. First, you need to get the path to the view template file (remember, it might be overridden!) using Joomla's \Joomla\CMS\Plugin\PluginHelper::getLayoutPath method:

$path = \Joomla\CMS\Plugin\PluginHelper::getLayoutPath(
  'system', 'example', 'foobar'
);

The three arguments are the plugin folder, the plugin name, and the view template name. In this case, we are looking for the foobar.php view template file inside plugins/system/example/tmpl (or its override in the current template).

The second step is include this file and capturing its output:

ob_start();
include $path;
$html = ob_get_clean();
[Note]Note

If you are writing a custom field plugin you will NOT be directly accessing the view template file. This is done for you by the \Joomla\Component\Fields\Administrator\Plugin\FieldsPlugin core class your plugin extends from.