XaminProject / handlebars.php

Handlebars processor for php
331 stars 132 forks source link

`if` block helper does not work with `else` #2

Closed joshpangell closed 11 years ago

joshpangell commented 11 years ago

The standard if else block is not rendering properly. This example is strait from the Handlebars.js website.

$h = new Handlebars_Engine;

echo $h->render(
        '<div class="entry">
          {{#if author}}
            <h1>{{author.firstName}} {{author.lastName}}</h1>
          {{else}}
            <h1>Unknown Author</h1>
          {{/if}}
        </div>
        ', 
        array(
            'author' => array(
                'firstName' => "Charles", 
                'lastName' => "Jolley"
            )
        )
    );

Output:

<div class="entry">
    <h1>Charles Jolley</h1>
    <h1>Unknown Author</h1>
</div>

The else block is not being registered as a helper name. This can be parsed inside of the if helper method, however, I am having troubles rendering the correct template source.

Example:

$this->add(
    'if', 
    function ($template, $context, $args, $source) {
        $tmp = $context->get($args);
        $buffer = '';
        $elsepos = strpos($source, "{{else}}");
        if ($elsepos !== false) {
            if ($tmp) {
                // Handles the "if" case
                $source = substr($source, 0, $elsepos);
            } else {
                // Handles the "else" case
                $source = substr($source, $elsepos+9);
            }
        }
        if ($tmp) {
            $buffer = $template->render($context);
        }            
        return $buffer;
    }
);
everplays commented 11 years ago

thanks for the report. it's fixed now.

$h = new Handlebars_Engine;

echo $h->render(
        '<div class="entry">
          {{#if author}}
            <h1>{{author.firstName}} {{author.lastName}}</h1>
          {{else}}
            <h1>Unknown Author</h1>
          {{/if}}
        </div>
        ', 
        array(
            'author' => array(
                'firstName' => "Charles", 
                'lastName' => "Jolley"
            )
        )
    );

produces:

<div class="entry">
            <h1>Charles Jolley</h1>
 </div>

also

$h = new Handlebars_Engine;

echo $h->render(
        '<div class="entry">
          {{#if author}}
            <h1>{{author.firstName}} {{author.lastName}}</h1>
          {{else}}
            <h1>Unknown Author</h1>
          {{/if}}
        </div>
        ', 
        array(
            'author' => false
        )
    );

produces:

<div class="entry">
            <h1>Unknown Author</h1>
</div>
fzerorubigd commented 11 years ago

A better way in ec6761fde447282d31fe4ac369f658159a09a259