zordius / lightncandy

An extremely fast PHP implementation of handlebars ( http://handlebarsjs.com/ ) and mustache ( http://mustache.github.io/ ),
https://zordius.github.io/HandlebarsCookbook/
MIT License
608 stars 76 forks source link

Custom condition helper over payload array with conditions #356

Open jmares79 opened 2 years ago

jmares79 commented 2 years ago

Hi all, great library!!

I'm trying to build a custom helper in order to compare, for example, 2 strings. One argument of the condition should be an attribute in the payload and the 2nd one either a constant string or another variable.

So far what I have done, by checking the docs, is:

The PHP Code:

require('./vendor/autoload.php');
use LightnCandy\LightnCandy;

// The Template:
$template = <<<VAREND
<div>{{#if_eq name 'SOME NAME'}}<div><h1>IS EQUAL</h1><div>{{/if_eq}}</div>
<div>{{#if_eq name attribute}}<div><h1>IS EQUAL</h1><div>{{/if_eq}}</div>
VAREND;

// Helpers:
$helpers = array(
  '"if_eq" => function ($arg1, $arg2) {
           return $arg1 == $arg2;
    }
);

$phpStr = LightnCandy::compile($template, array(
  // Used compile flags
  'flags' => LightnCandy::FLAG_ERROR_EXCEPTION | LightnCandy::FLAG_HANDLEBARS,
  'helpers' => $helpers
));

echo "Generated PHP Code:\n$phpStr\n";

// Input Data:
$data =[
      "name" => "SOME NAME"
      "attribute" => "SOME NAME"
];

// Save the compiled PHP code into a php file
file_put_contents('render.php', '<?php ' . $phpStr . '?>');

// Get the render function from the php file
$renderer = include('render.php');

echo "Result:\n" . $renderer($data);
1

The Issue:
----------

The result of the helper is "<div>1</div>", and I would have expected the HTML in the middle of the operator to be shown. Obviously I'm missing something or I misunderstood the way that custom block helpers are built.

Does anyone know what is the correct way of implementing something like that?

Regards!