Skip to content
inghamn edited this page Oct 23, 2013 · 1 revision

Helpers

Helpers are Template class functions that generate output. They are useful for output content that needs to be repeated in multiple places in the site.

Template Helpers are specific to each possible outputFormat. For instance, an HTML template helper is probably not needed when the template renders itself as JSON or XML. However, there may be additional JSON or XML template helpers.

Using a helper

Two steps are required; having the template load a helper object, then calling the specific helper function. This is most commonly done from inside a Block. However, it can be done anywhere you have access to a Template object.

<?php
	$helper = $this->template->getHelper('formatDuration');
	echo $helper->formatDuration(120);

When helpers are used from inside a block, it is implicit that the Template has already chosen an outputFormat. When loading a helper, the template will only look for helpers in it's current outputFormat directory.

Creating helpers

Helpers are simple PHP classes. The function name, class name, and file name must all match. The naming scheme is what allows the template to quickly find and load the correct PHP file. In the example above, the we would have a RenderInputs.php file, which declares a RenderInputs class. The RenderInputs class must have a renderInputs() function.

The function code can be anything, and the function parameters should be whatever parameters are needed. The only requirement is that the function return an output string. Here's an example from uReport:

<?php
class FormatDuration
{
	public function __construct() { }

	public function formatDuration($durationInSeconds) {
		$duration = '';
		$days     = floor($durationInSeconds / 86400);
		$durationInSeconds -= $days * 86400;
		$hours    = floor($durationInSeconds / 3600);
		$durationInSeconds -= $hours * 3600;
		$minutes  = floor($durationInSeconds / 60);
		$seconds  = $durationInSeconds - $minutes * 60;

		if     ($days    > 0) { $duration = "$days days";       }
		elseif ($hours   > 0) { $duration = "$hours hours";     }
		elseif ($minutes > 0) { $duration = "$minutes minutes"; }
		else                  { $duration = "$seconds seconds"; }

		return $duration;
	}
}

Directory Structure

Helper files go inside of template outputFormat directories: /templates/$format/helpers/$class.php. The FormatDuration example above is an HTML helper. So it's filename would be: /templates/html/helpers/FormatDuration.php.

Clone this wiki locally