An #ifcond block helper for LightnCandy

This is rather specific, but if you're implementing Handlebars (in PHP) using LightnCandy, here's a great helper that lets you compare values and generate output accordingly.


Usage is similar to #if, but pass in two arguments:

{{#ifcond value 'something'}}
    Value equals something.
    Value does not equal something.

The else block is supported, but optional.

The code

Here you go. Make sure to enabled the correct flags:

$php = LightnCandy::compile($template, Array(
    'flags' => LightnCandy::FLAG_HANDLEBARSJS,
    'hbhelpers' => Array(

        'ifcond' => function() {

            // Get arguments
            $args = func_get_args();
            $context = $args[count($args) - 1];

            if( (string) $args[0] === (string) $args[1] ) {
                // Arguments match, render it
                return $context['fn']();
            } else {
                // If an {{else}} exists, render that instead; otherwise, render nothing
                return $context['inverse'] ? $context['inverse']() : '';

Author avatar

About the author

Creator of Surreal CMS and other web things. Follow me for tweets about JavaScript, CSS, and web programming.