Skip to content

Mustache helper methods

Mohamed Labib edited this page Feb 25, 2016 · 1 revision

How to inject helper methods inside mustache php

Part I The helper itself:

class Underscore
{

    /**
     * Called when class is called as a method
     * 
     * @access public
     * @param string $text actual text in mustache template as "{{param}}" for instance
     * @param object $mustache
     * @return string the processed output to replace the input passed to the method
     */
    public function __invoke($text, $mustache)
    {
        // $mustache->render($text) convert text from "{{param}}" to "value" held inside that param
        // Some dummy functionality for testing purpose to underscore the input (convert ParamValue to param_value )
        $inflector = new Inflector();
        return $inflector->underscore($mustache->render($text));
    }

}

Part II Injecting the helper inside mustache:

/**
 * Renderer Factory
 * 
 * Prepare Renderer service factory
 * 
 * 
 * 
 * @package customMustache
 * @subpackage service
 */
class RendererFactory implements FactoryInterface
{

    /**
     * Prepare Renderer service
     * 
     * 
     * @uses AuthenticationService
     * @uses \Mustache_Engine
     * @uses Renderer
     * 
     * @access public
     * @param ServiceLocatorInterface $serviceLocator
     * @return Renderer
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $config['helpers']['underscore'] = new Underscore();

        $engine = new \Mustache_Engine($this->setConfigs($config));
        $renderer = new Renderer();
        $renderer->setEngine($engine);
        return $renderer;
    }

Part III Using helper inside mustache templates

    # let's say {{ai.firstName}} holds "Foo" ,and {{ai.lastName}} holds "Bar"
    # then output here should be "foo_bar"
    <td>{{#underscore}}{{ai.firstName}} {{ai.lastName}}{{/underscore}}</td>