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

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

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

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

New Hampshirite building web apps in Florida. Creator of Surreal CMS, Postleaf, and DirtyMarkup.

Need to get in touch? Catch me on Twitter.