XaminProject / handlebars.php

Handlebars processor for php
331 stars 134 forks source link

Update Context::get to resolve @key and @index #35

Closed cgray closed 10 years ago

cgray commented 10 years ago

Change to allow @key and @index to be resolved within Context::get calls.

For Example to port this javascript helper

Handlebars.registerHelper("ifEquals", function (name, value,options){
    if (name == value) {
        return options.fn(this)
    }; 
});

Helpers that could accept @key and @index as parameters previously had to implemented like

$handleBars->addHelper("ifEquals", function ($template, $context, $args, $source){
    list($property, $value) = explode(" ", $args);
    if ($property == "@index"){
        $property = $context->lastIndex();
    } else if ($property == "@key") {
        $property = $context->lastKey();
    } else {
        $property = $context->get($value);     
    }
    if ($value == "@index"){
        $value = $context->lastIndex();
    } else if ($property == "@key") {
        $value = $context->lastKey();
    } else {
        $value = $context->get($value);     
    }
    if ($property == $value){
        return $template->render($context);
    }       
});

Can Now be implemented as

$handleBars->addHelper("ifEquals", function ($template, $context, $args, $source){
    list($property, $value) = explode(" ", $args);
    if ($context->get($property) == $context->get($value)){
        return $template->render($context);
    }       
});
everplays commented 10 years ago

Could you please remove the @index and @key stuff from _getVariable method of Template class? Those won't be required anymore. Also add yourself as author to both files, please.

cgray commented 10 years ago

Removed @index and @key lines from Template::__getVariable, also added support for quoted literal strings as part of the Context::get call. Now Parameters that are passed in quoted will be treated as string literal instead of a variable name. Example:

{{#ifEquals message "You've Got Mail"}}<img src='/icons/mail.gif'/>{{/ifEquals}}

Also added Template::parseArguments as a helper function to ease breaking the argument list property.

The above example will be broken into an array containing:

message
"You've Got Mail"

as opposed to what you would get from a call to implode with space as the delimiter.

Should more closely emulate what happens on handlebars.js

everplays commented 10 years ago

thanks.