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
610 stars 76 forks source link

"xif" helper, input datas within expression not interpreted #287

Closed gwenael74 closed 6 years ago

gwenael74 commented 6 years ago

The PHP Code:

// The Template:
<p>
    {{#xif " name == 'Sam' && age === '12' " }}
        BOOM
    {{else}}
        BAMM
    {{/xif}}
</p>

// Helpers:
'helpers' => Array(
    .....
    .....
    'xif' => function ($expression, $options) {
        // Here, "$expression" value is:
        // name == 'Sam' && age === '12'
        // => the param "$expression" is not interpreted :-/

        if (eval($expression)) { // => Unfortunately, this line will generate an error :-(
            return $options['fn']();
        } else {
            return $options['inverse']();
        }
    }
)

// My flags
'flags' => LightnCandy::FLAG_ERROR_EXCEPTION | LightnCandy::FLAG_ELSE | LightnCandy::FLAG_HBESCAPE | LightnCandy::FLAG_JS | LightnCandy::FLAG_ERROR_LOG | LightnCandy::FLAG_ADVARNAME | LightnCandy::FLAG_HANDLEBARSJS | LightnCandy::FLAG_HANDLEBARSJS_FULL,

// Input Data:
$data = array(
  'name' => 'Sam',
  'age' => '12'
);

The Issue:

Hello, I have a question. I tried all this afternoon to recreate this javascript helper "xif": https://gist.github.com/akhoury/9118682 (which work fine on my client side)

Howerver In PHP side, I didn't handle to make it work (my other helpers are working fine, only this one in which I've got difficulties).

How to create such helper which could work with any expression? (I am on the master branch, updated yesterday)

Thanks you for your help Gwen

zordius commented 6 years ago

Sorry for the long time waiting.

Your question is about PHP syntax. the code name == 'Sam' && age === '12' is only valid in JavaScript but not in PHP, a quick refine should be something like this: $name == 'Sam' && $age === '12' . Then you should encounter another problem what these variables ($name and $age) are not presented in local , I think you need to redesign the xif helper to make it work for both PHP and JS.

gwenael74 commented 6 years ago

It's what I did actually, I redesigned it Thanks you

skynetweb commented 4 years ago

It's what I did actually, I redesigned it Thanks you

How did you fixed that, i'm also interested because i'm facing the same issue