Advanced search

How template hooks work

Template hooks is a mechanism that allows plugins to insert generated output at specific locations. Plugins can register template fragments, which are chainable so that multiple plugins can populate the same hook position.

Lets assume, a plugin wants to extend the user block in the sidebar (the small block where the member's avatar, nick name and stats appear). First, the plugin must use a code hook (not discussed here, but the method is very similar to SMF) to generate the output. For example, a plugin could hook load_userdata to extend the $user_info array with its own data ,child?.

Of course, collecting data is fine, but we also need a way to display it. The typical method in SMF (and other forum systems) is to modify the template code and add a few lines of code to display our new data. While this works fine, it is complex and bears a lot of problems. So, there must be an easier way and template hooks are exactly what we need here.

First, the plugin must register the template fragments to extend the user block in the sidebar. Since this user block is only visible on the board index, it's best to use the boardindex hook for this purpose. So we hook into boardindex with a small function

Code: php
class MyPlugin {
  public static function boardindex_hook() // runs only in board index
      // add our plugin directory to the list of directories to search for templates.
      // register our hook template
    EoS_Smarty::getConfigInstance()->registerHookTemplate('sidebar_userblock', 'myplugin_userblock');

sidebar_userblock is the name of the template hook we want to use. There are many, many template hooks in various positions of the templates, so it is important to choose the proper one.

We must then write a new template myplugin_userblock.tpl and store it in our plugin's root directory (what $_dir points to in the example above). Note that the extension .tpl is always omitted when working with templates, it's assumed to be the default filename extension for all templates.

Code: php
<div class="flat_container mediumpadding">
  {$U.mydata}    {* output what we have added to $user_info *}

If all goes well, our output should appear at the bottom of the user block in the boardindex side bar. So basically, template hooks allow to extend existing templates without the need to modify them. Right now, there are only a few template hooks and they only work in the new smarty templates, but the system will be gradually extended over time to allow for a flexible plugin architecture and little need to modify existing templates.

Page generation time: 0.081 seconds