XaminProject / handlebars.php

Handlebars processor for php
331 stars 134 forks source link

how to create an equals helper #58

Closed jonas-db closed 10 years ago

jonas-db commented 10 years ago

Hi,

i'm having difficulties to implement an equals helper in this php framework. It should be like {{#equals variable string}}test{{/equals}}

I know i can do the following:

$engine->addHelper('equals', function ($template, $context, $args, $source) { var_dump($context->get($args)); // ??? });

but i fail to see what these parameters do or how they have to be used in a correct way.

I'm sorry to post this question here but i don't see to find an answer anywhere. An little example or explanation would be nice :)

Thanks!

JustBlackBird commented 10 years ago

Hi,

You can use something like this:

$engine->addHelper('ifEqual', function($template, $context, $args, $source) {
    $parsed_args = $template->parseArguments($args);
    if (empty($parsed_args) || count($parsed_args) < 2) {
        return '';
    }

    $condition = ($context->get($parsed_args[0]) == $context->get($parsed_args[1]));

    if ($condition) {
        $template->setStopToken('else');
        $buffer = $template->render($context);
        $template->setStopToken(false);
    } else {
        $template->setStopToken('else');
        $template->discard();
        $template->setStopToken(false);
        $buffer = $template->render($context);
    }

    return $buffer;
});

After the helper is registered, you can use the following in a template:

{{#ifEqual first second}}
    The first argument is equal to the second one.
{{else}}
    The arguments are not equal.
{{/ifEqual}}

Hope it helps.

jonas-db commented 10 years ago

I had just figured it out how it was working pretty much :) although your example did help me a bit and it might help others too.

Thanks for the efforts!