Code Monkey home page Code Monkey logo

handlebars.php's Introduction

Handlebars.php

Build Status Scrutinizer Quality Score Code Coverage installation

add the following to require property of your composer.json file:

"xamin/handlebars.php": "dev-master" for php 5.3+ "xamin/handlebars.php": "dev-php-52" for php 5.2

then run:

$ composer install

usage

<?php

// uncomment the following two lines, if you don't use composer
// require 'src/Handlebars/Autoloader.php';
// Handlebars\Autoloader::register();

use Handlebars\Handlebars;

$engine = new Handlebars;

echo $engine->render(
    'Planets:<br />{{#each planets}}<h6>{{this}}</h6>{{/each}}',
    array(
        'planets' => array(
            "Mercury",
            "Venus",
            "Earth",
            "Mars"
        )
    )
);
<?php

use Handlebars\Handlebars;

$engine = new Handlebars(array(
    'loader' => new \Handlebars\Loader\FilesystemLoader(__DIR__.'/templates/'),
    'partials_loader' => new \Handlebars\Loader\FilesystemLoader(
        __DIR__ . '/templates/',
        array(
            'prefix' => '_'
        )
    )
));

/* templates/main.handlebars:

{{> partial planets}}

*/

/* templates/_partial.handlebars:

{{#each this}}
    <file>{{this}}</file>
{{/each}}

*/

echo $engine->render(
    'main',
    array(
        'planets' => array(
            "Mercury",
            "Venus",
            "Earth",
            "Mars"
        )
    )
);

contribution

contributions are more than welcome, just don't forget to:

  • add your name to each file that you edit as author
  • use PHP CodeSniffer to check coding style.

license

Copyright (c) 2010 Justin Hileman
Copyright (C) 2012-2013 Xamin Project and contributors

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

handlebars.php's People

Contributors

boukeversteegh avatar cgray avatar davestein avatar davidcramer avatar daviddeutsch avatar diosney avatar everplays avatar fellars avatar fzerorubigd avatar hfhchan avatar jeffturcotte avatar joeybaker avatar jslegers avatar justblackbird avatar maadhattah avatar mai7star avatar marrynka avatar mmontagna avatar ryan-mahoney avatar soncodi avatar szicsu avatar thormeier avatar ulriklystbaek avatar zemistr avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

handlebars.php's Issues

how to create an equals helper

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!

Package / Naming thoughts

Minor recommendations:

  • Add "Handlebars" as a namespace to all classes
  • Enable true autoloading via composer
  • Remove underscores from class names
  • Consider changing Handlebars_Engine to simply Handlebars

Then to use the class, we would do:

use Handlebars\Handlebars;

Handlebars->template($template, $data);

Helpers not passed correct this value within each block

When trying to pass a helper function an argument inside of an each loop, I get the string this passed as the argument to the helper, rather than the current value of the each loop.

$engine->addHelper('foo', function($template, $context, $arg){
  return new \Handlebars\SafeString( '<strong>' . $arg. '</strong>' );
}); 

echo $engine->render(
  'Planets:<br />{{#each planets}}<h6>{{foo this}}</h6>{{/each}}',
  array(
    'planets' => array(
      'Mercury',
      'Venus',
      'Earth',
      'Mar'
    )   
  )   
);

Outputs:

Planets:<br /><h6><strong>this</strong></h6><h6><strong>this</strong></h6><h6><strong>this</strong></h6><h6><strong>this</strong></h6>

Whereas if I don't call a helper inside of the each loop, I get the correct value:

echo $engine->render(
  'Planets:<br />{{#each planets}}<h6>{{this}}</h6>{{/each}}',
  array(
    'planets' => array(
      'Mercury',
      'Venus',
      'Earth',
      'Mar'
    )   
  )   
);

Outputs:

Planets:<br /><h6>Mercury</h6><h6>Venus</h6><h6>Earth</h6><h6>Mar</h6>

I'm attempting to use the same Handlebar templates server side and client side, and this is preventing me from doing that.

Support for @first and @last in #if helper

Apparently @FIRST and @last work in the #if helper now, but not in handlebars.php. See: handlebars-lang/handlebars.js#483

You can get around this somewhat using @index due type coercion:

{{#unless @index}}This is the first element{{/unless}}
{{#if @index}}This is not the first element{{/if}}

...But really, these should be implemented to maintain consistency with Handlebars syntax.

I may get some time to work on this today and will issue a pull request if so.

"if" block helper stopped working with "else"

The if else block helper was previously working correctly, but since the previous release 3079518 (fixing the looping issue), it no longer works.

Note: all work with 600215d

Testing methods

// If
$h = new Handlebars_Engine;

echo $h->render(
    'If:
    <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"
        )
    )
);

// Else
$h = new Handlebars_Engine;

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


// If with loop
$h = new Handlebars_Engine;

echo $h->render(
    'If with a loop:
    <div class="entry">
      {{#if author}}
        {{#author}}<h1>{{firstName}} {{lastName}}</h1>{{/author}}
      {{else}}
        <h1>Unknown Author</h1>
      {{/if}}
    </div>
    ', 
    array(
        'author' => array(
            array(
                'firstName' => "Nikola", 
                'lastName' => "Tesla"
            ),
            array(
                'firstName' => "Carl", 
                'lastName' => "Segan"
            ),
            array(
                'firstName' => "Neil", 
                'lastName' => "Degrasse Tyson"
            )
        )

    )
); 

Result

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


Else:
<div class="entry"></div>


If with a loop:
<div class="entry">
    <h1>Nikola Tesla</h1>
    <h1>Carl Segan</h1>
    <h1>Neil Degrasse Tyson</h1>
</div>

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

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;
    }
);

How access $context->var

Hi,

Inside a custom helper, how can I access the variables inside $context, which are passed down to the helper via $handlebars_instance->render($template, $LOM)?

For instance, if $LOM->var, I would like to do something like:

public static function _helper_compile_content($template, $context, $args, $source) {
       $tmp = $context->var; // This won't work. How get var from the $context?
}

If I do a `var_dump($context)` I see the variable there, but since it is marked as private I can't access it directly.

(sorry if this is straightforward, I'm a noob in PHP regards)

Migrate to MIT license?

I would like to intergate your code in our application, but the dobclock code @license states that it is licensed under the GPLv3 license.

Is it possible to migrate the library to MIT or some other license like LGPL?

Pass an instance of \Handlebars\Arguments to a helper

It will be more convenient if a helper receives an instance of \Handlebars\Arguments instead of arguments string. In this case a helper should know nothing about parsing and just uses already prepared arguments. Also if we parse an arguments string before calling a helper we can guarantee that arguments string is valid.

I could provide a pull request, if the maintainers are interesting in it.

Equality check helper

Hi,

Currently the if helper doesn't support equality checks and I'm in needed of that.

I implemented an equality check helper in JavaScript, as defined in:

                    ´´´javascript
                    // Need to check if a conditional statement is true or false.
        Handlebars.registerHelper('equal', function (lvalue, rvalue, options) {
            if (arguments.length < 3)
                throw new Error('Handlebars Helper equal needs 2 parameters');
            if (lvalue != rvalue) {
                return options.inverse(this);
            } else {
                return options.fn(this);
            }
        });

And is used like this:

                   ´´´javascript
                   {{#equal options.type "1-2+1-2"}}
                             Some content here.
                   {{/equal}}

I'm trying to convert that helper into Handlebars.PHP, but I'm having a hard time.

Can you help me on this?

Thanks!

Zero before closing tag causes parser error

Super specific error: if you have a single 0 before a closing tag for a condition, like this...

{{#if someVar}}0{{/if}}

...the parser gives you the following error:

Unexpected closing tag: /0if on line 78 in [...]/xamin/handlebars.php/src/Handlebars/Parser.php

The issue also happens if there's an {{else}} tag but still only a single 0 between it and the closing tag, like so:

{{#if someVar}}anything{{else}}0{{/if}}

It only happens with exactly a 0 – the following examples work correctly:

{{#if someVar}}1{{/if}}  {{! Works }}
{{#if someVar}} 0{{/if}} {{! Works }}
{{#if someVar}}a{{/if}}  {{! Works }}

Helpers auto escape and triple braces syntax

I've found differences between handlebars.js and handlebars.php.

Handlebars.js automatically escape result of line helper if it was not wrapped into Handlebars.SafeString object. To disable this behavior and display results "as is" three braces ({{{) are used for helpers.

Handlebars.php does not escape result of line helpers automatically. Thus three braces does not have any sense for line helpers.

This leads to different results for the same templates.

To illustrate the problem i've made tests for js version (http://jsfiddle.net/eSH6s/3/) and php version (Mibew@390bc70).

"if/else" block helper does not work with loops

Related to issue #2, loops do not work in conditionals.

The first proposed fix for the if else issue in commit 600215d actually does work, however the most recent fix in commit b9b6383 does not.

Example:

$h = new Handlebars_Engine;

echo $h->render(
        '<div class="entry">
          {{#if author}}
            {{#author}}<h1>{{firstName}} {{lastName}}</h1>{{/author}}
          {{else}}
            <h1>Unknown Author</h1>
          {{/if}}
        </div>
        ', 
        array(
            'author' => array(
                array(
                    'firstName' => "Nikola", 
                    'lastName' => "Tesla"
                ),
                array(
                    'firstName' => "Carl", 
                    'lastName' => "Segan"
                ),
                array(
                    'firstName' => "Neil", 
                    'lastName' => "Degrasse Tyson"
                )
            )

        )
    ); 

The latest commit, b9b6383, will render incorrectly

<div class="entry">
    <h1>Nikola Tesla</h1>
</div>

Commit 600215d will render correctly

<div class="entry">
    <h1>Nikola Tesla</h1>
    <h1>Carl Segan</h1>
    <h1>Neil Degrasse Tyson</h1>
</div>

No support for ArrayLoader

Hi,

When do you plan on implementing the ArrayLoader? The engine lacks support for loading an array of partials on instantiation which limits the location of all partials to just one predefined folder if using the FilesystemLoader. This doesn't allow one to create flexible template systems within their app where the partials can be located in different locations depending on their purpose e.g.

-> layout.handlebars
-> header.handlebars
-> footer.handlebars
-> sidebar.handlebars

-> widgets/
--> calendar.handlebars

-> blocks/
--> breadcrumb.handlebars
--> menu.handlebars
--> pagination.handlebars

-> contentblocks/
--> list.handlebars
--> edit.handlebars
--> table.handlebars

unable to "0" as an array key in HandleBars_Context

HandleBars_Context#247 uses empty($inside) which returns true for the string "0"

thus preventing use of tags such as "array.0.name"

suggestion:
if (($inside !== "0" && empty( $inside )) || ( $inside == 'this' ) ) {

Handlebars.js like helpers

At the moment writing custom helpers is complicated for users who does not familiar with internal architecture of Handlebars.php. One should manually parse arguments, gets them from the context, render nested blocks, works with else section and so on.

Is there any chance a simple, Handlebars.js like, interface will be implemented for helpers?

'this' does not work with 'each' iterator

As described on the http://handlebarsjs.com/ website.

<ul class="people_list">
  {{#each people}}
  <li>{{this}}</li>
  {{/each}}
</ul>

when used with this context:

{
  people: [
    "Yehuda Katz",
    "Alan Johnson",
    "Charles Jolley"
  ]
}

will result in:

<ul class="people_list">
  <li>Yehuda Katz</li>
  <li>Alan Johnson</li>
  <li>Charles Jolley</li>
</ul>

Currently it'll iterate through but it does not render the content for {{this}}, instead it is left blank.

Commenting out expressions doesn't work as expected

It's unclear to me whether it's possible to comment out expressions and have handlebars.php completely ignore anything in a comment, which is possible in pretty much every programming language and commonly used for temporarily storing deleted code that may be fully or partially restored at a later time.

Currently, handlebars.php tries to parse any {{ }} it can find as an expression, including those within comments. This results in a fatal error when no helper can be found with that name.

That means I can't do this :

<!--
<html>
    <body>
        Hello {{name}}</br>
        You have just won ${{value }}!</br>
        {{#in_ca}}
        Well, ${{taxed_value}}, after taxes.</br>
        {{/in_ca}}
    </body>
</html>
-->

This also doesn't work :

{{!-- comment}}
<html>
    <body>Hello {{name}}</br>
        You have just won ${{value}}!</br>
        {{#in_ca}}
        Well, ${{taxed_value}}, after taxes.</br>
        {{/in_ca}}
    </body>
</html>
{{comment --}}

This doesn't work either :

{{!--
<html>
    <body>Hello {{name}}</br>
    You have just won ${{value}}!</br>
    {{#in_ca}}
    Well, ${{taxed_value}}, after taxes.</br>
    {{/in_ca}}
    </body>
</html>
--}}

Neither does this :

{{!-- <html><body>Hello {{name}}</br>You have just won ${{value}}!</br>{{#in_ca}}</br>Well, ${{taxed_value}}, after taxes.{{/in_ca}}</body></html> --}}

Whatever I try, I keep getting the following error :

<b>Fatal error</b>:  Uncaught exception 'RuntimeException' with message 'in_ca is not registered as a helper' in /var/www/monitoring/Vendor/Handlebars/Template.php:349
Stack trace:
#0 /var/www/monitoring/Vendor/Handlebars/Template.php(404): Handlebars\Template-&gt;_mustacheStyleSection(Object(Handlebars\Context), Array)
#1 /var/www/monitoring/Vendor/Handlebars/Template.php(162): Handlebars\Template-&gt;_section(Object(Handlebars\Context), Array)
#2 /var/www/monitoring/Vendor/Handlebars/Handlebars.php(173): Handlebars\Template-&gt;render(Object(Application\View_Model))
#3 /var/www/monitoring/dashboard.php(46): Handlebars\Handlebars-&gt;render('&lt;!DOCTYPE html&gt;...', Object(Application\View_Model))
#4 {main}
  thrown in <b>/var/www/monitoring/Vendor/Handlebars/Template.php</b> on line <b>349</b><br />

This isn't how I expect comments to work.

php-52 branch needs support for special variables: @last, @first

I see that in the current master branch there is support for the EachHelper variables @last, @first, etc.

From EachHelper.php:

$specialVariables = array(
    '@index' => $index,
    '@first' => ($index === 0),
    '@last' => ($index === $lastIndex),
);
if (!$isList) {
    $specialVariables['@key'] = $key;
}

But those are missing from the php-52 branch. It would be really great to have those in the php-52 version of this script!

I have been trying to add support by modifying the Helpers.php file in php-52 and adding similar code in the _helper_each() function, but I am having trouble figuring out how to get it to work.

With Versioning for Composer

I know Handlebars is under development right now, however when I tried to install it via Composer, it doesn't want to install it because it would get it from dev-master.

The solution for this issue would be to create a tag on each update that is critical.

Can you please start releasing the small version by tagging them?

Thank you

FilesystemLoader and Testing

I just swapped my templates from mustache to handlebars using this lib. I have a unit test to verify that given a certain file, it will return a certain output.

// Calls Handlebars loadTemplate and then render on the template
$output = $this->_templater->view( 'place', [ 'friend' => 'Person' ] );
$this->assertEquals( '<body><p></p>Hello Person</body>', $output );

I am using https://github.com/mikey179/vfsStream to mock the file system, but that doesn't work with this lib because of realpath being used in the constructor.

The directory comes in as vfs://mydir. You can see in this popular Mustache loader, how they handle it:
https://github.com/bobthecow/mustache.php/blob/master/src/Mustache/Loader/FilesystemLoader.php#L52

What do you think?

Outdated stable release

I maintain a library that depends on this, which doesn't work with the latest stable (0.8.0 at the time of this writing), but does work with dev-master. I have to ask users of my library to set minimum-stability to dev in their root composer.json or to add this library to their root composer.json with a @dev flag.

There hasn't been a stable release in almost a year. Can we get an 0.9.0 tag? Thanks!

Iterator block and list block throw exceptions

I first tried using the standard {{#}} iterator method:

$h = new Handlebars_Engine;
echo $h->render(
        'Planets:<br> {{#planets}}<h6>{{planet}}</h6>{{/planets}}', 
        array(
            'planets' => array(
                'planet' => "Mercury",
                'planet' => "Venus",
                'planet' => "Earth",
                'planet' => "Mars"
            )
        )
    );

Error:

Fatal error: Uncaught exception 'RuntimeException' with message 'planet is not registered as a helper' in Handlebars/Template.php:172

When that did not work out, I tried to use the {{#list}} iterator:

$h = new Handlebars_Engine;
echo $h->render(
        'Planets:<br> {{#list planets}}<h6>{{planet}}</h6>{{/list}}', 
        array(
            'planets' => array(
                'planet' => "Mercury",
                'planet' => "Venus",
                'planet' => "Earth",
                'planet' => "Mars"
            )
        )
    );

Error:

Fatal error: Uncaught exception 'RuntimeException' with message 'list is not registered as a helper' in Handlebars/Template.php:172

usage of helper

Hi,
I'm trying already for few days to understand how it's working without success.

    $render = new Handlebars_Engine();
     $render->addHelper('toLower',
          function($value) {
            echo $value;
            return strtolower((string) $value);
          }
        );

in template

    {{ 'test0' }}
    {{ toLower 'TEST1' }}
    {{{ toLower 'TEST2' }}}

no result and the helper is not accessed

if I'm doing

    {{#toLower}}TEST3{{/toLower}}

the method is accessed but the value is a template
Thanks

Render with partials

$engine = new Handlebars();
$data = [];

// I don't need global partials
//$engine->registerPartial('partial_1', '<span />');
//$engine->registerPartial('partial_2', '<span />');
//$engine->render('<div />', $data)

// more dynamically
$engine->render('<div />', $data, [
  'partial_1' => '<span />',
  'partial_2' => '<span />',
]);

$engine->render('<div />', $data, [
  'partial_1' => '<span />',
  'partial_3' => '<span />',
]);

README.markdown

Hey!

can you tell whats going on with the project on the README file?
is it stable?
whats the api for it?

this guy looks promising!

Backslash doesn't work

Things like \pi remove the backslash and \pi shows the double backslash. Handlebars.js is works fine.

Inline helper methods

Hey guys, stellar work on this port.

I am having trouble on rendering singular helpers. For example,

{{fullName author}}

fullName being the name of the helper. It works fine if I have a # at the beginning, signifying a block expression. Is there functionality ported to register singular helpers to be used without a # ? If so, what do I need to do to register that helper.

If not, would it be difficult to put it in ?

New stable release

The last stable release was published 3 months ago. At the moment there are three bug fixes (#84, #86, #89) and two improvements (#94, #96) in the master branch. I believe it's time to publish new stable release.

Adding complex dynamic data to helpers and sub-templating from custom helpers

I'm currently experimenting with the following features.

Sub-templating

Syntax :

<div class="site-body">
    <div class="site-center">
        <div class="cell">
            {{{template panel this name}}}
        </div>
    </div>
</div>

Explanation :

  • It includes a template called panel at this very spot
  • It passes the data for {{this}} and {{name}} to the template

Passing data to helpers

The problem with the syntax {{{template panel this name}}} is that it's rather restrictive in naming of parameters that are past to a subtemplate (or other helper).

To allow more custom naming, alternate syntaxes could be :

{{{template panel data=this&name=John}}}
{{{template panel data=this name=John}}}
{{{template panel data=this;name=John}}}
{{{template panel data=this,name=John}}}
{{{template panel data=this-name=John}}}

See also #44

The problem with these syntaxes, is distinguishing between what content should passed literally (eg. John) and what content should passed as a reference (eg. this). Variations on this syntax that add this distinction would be :

{{{template panel data=this&name="John"}}}
{{{template panel data=this&name='John'}}}
{{{template panel data={{this}}&name=John}}}
{{{template panel data=$this&name=John}}}
{{{template panel data=${this}&name=John}}}

As any content in between a beginning and end tag remains unparsed for custom helpers, there are nevertheless still many alternatives worth considering :

{{#template panel}}
<input type="array" name="data" value="{{this}}" />
<input type="string" name="name" value="John" />
<output type="string" name="panel" />
<!-- This syntax would even allow you to store the output -->
<!-- of the template as a variable named panel -->
{{/template}}
{{#template panel}}
<parameters>
    <array data="{{this}}" />
    <string name="John" />
</parameters>
{{/template}}
{{#template panel}}
<input>
    <array data="{{this}}" />
    <string name="John" />
</input>
<output>
    <string panel />
</output>
{{/template}}
{{#template panel}}
<template>
    <parameter data="{{this}}" />
    <parameter name="John" />
</template>
{{/template}}
{{#template panel}}
data : (array) {{this}}
name : (string) John
{{/template}}
{{#template panel}}
data = {{this}}
name = John
{{/template}}

Would you be interested in adding any of these syntaxes to the XaminProject/handlebars.php library? I am still considering which syntax to use for my own PowerTools project and I figured I might as well contribute the syntax I eventually choose to the XaminProject/handlebars.php project if anyone is interested.


EDIT :

See also handlebars-lang/handlebars.js#817

typo in engine

line 194
get function should be __get
Kind Regards,
Paul

Partial parameters

So when I load in a hbs file that uses a partial

<div class="topics-search">
  <input type="text" class="topics-search__text-input">
  <button class="topics-search__submit">
    {{> icon iconClass=search}}
  </button>
</div>

I get the following error

Fatal error: Uncaught exception 'InvalidArgumentException' with message 'variable name is invalid' in includes/handlebars.php/src/Handlebars/Context.php:301 
Stack trace: 
#0 includes/handlebars.php/src/Handlebars/Context.php(237): Handlebars\Context->_splitVariableName('iconClass='sear...') 
#1 includes/handlebars.php/src/Handlebars/Template.php(503): Handlebars\Context->get('iconClass='sear...') 
#2 includes/handlebars.php/src/Handlebars/Template.php(241): Handlebars\Template->_partial(Object(Handlebars\Context), Array) 
#3 includes/handlebars.php/src/Handlebars/Template.php(180): Handlebars\Template->_renderInternal(Array, Object(Handlebars\Context)) 
#4 includes/handlebars.php/src/Handlebars/Handlebars.php(184): Handlebars\Template->render(A in includes/handlebars.php/src/Handlebars/Context.php on line 301

I don't know why my partial variable is getting rejected or what is wrong with my variable name. There isn't much documentation on this either. I am not sure if there is a bug breaking this, or if I am just doing it wrong.

Handlebars subexressions not supported yet

Since v1.3.0, handlebars.js supports subexpressions in helper calls, like {{ foo (bar 3) }}.

In handlebars.php, using such an expression raises a 'InvalidArgumentException' with message 'variable name is invalid'.

Any chance this will get implemented soon?

Is whitespace deletion supported

The handlebar has {{prop}} or {{prop}} that eats up all whitespace on the left or right of the generated string. Is this supported?

How pass @index as parameter to custom helper

Setup:

- A custom helper content that expects two parameters a collection and an index.

- An #each helper invocation that calls to #content helper, like this:

{{#each data}} {{#content ../parent_options @index}}{{/content}} {{/each}}

The issue:

Inside the content helper definition I want to access the @Index value, say 0,1,2,... but I'm only getting a string!

How can pass as a parameter and access inside the content helper definition the value of @Index?

IfHelper/UnlessHelper don't support string literals as argument

Code like {{#if "yes"}}yes{{/if}} in a template results in an exception.

This is also a problem when testing the result of a subexpression, because subexpression results are passed around as quoted strings.

handlebars.js swallows string literals as if/unless arguments, and the empty string evaluates as falsy.

Escaping curly brackets

Does handlebar provide a way for escaping curly brackets. I've tried the js version
/{{test}} gives {{test}}

However, php version does not and render an empty string (because data is empty)

No way to generate \\{{var}}

Correct result of (context is ['var' => 'value']) :

\\\{{var}}

is

\value

but handlebars.php produce

\\{{var}}

The MIT license only has *one* condition…

And somehow you managed to violate it.

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

Not cool, guys.

Should context misses trigger exceptions?

If I have a template like this:
{{#Item}}
...
{{/Item}}

And the hash I pass it does not have an "Item" key I expect the template to simply skip the block, but in handlebars.php it throws an exception. I'm not 100% sure this is either the correct or incorrect behavior, but I assumed it would simply skip the block. I'm basing this assumption on the mustache spec:
(github.com/mustache/spec/blob/master/specs/sections.yml)
see 'Failed context lookups should be considered falsey'

I can submit a pull request if this should be changed to simply skip the block.

Better testing

At the moment there are too many incompatibilities between Handlebars.js and Handlebars.php versions. I believe we should use Handlebars.js specs and review all test cases.

Nested {{#each}} not working!

In the following code, adding a nested {{#each}} breaks the context of the parent {{#each}} and does not output anything, as if the 'players' array were empty.

        {{#each teams}}
        <div class="column-1-2 roster-team">
            <div class="roster-team-heading">
                <span class="roster-team-name">
                    {{name}}:
                </span>
                <span class="roster-team-locker-room">
                    {{locker_room}}
                </span>
                <span class="roster-team-jersey-color">
                    ({{jersey}})
                </span>
            </div>
            <div>
                {{#each players}}
                <div class="roster-team-player">
                    <div class="roster-team-player-number">
                        1.
                    </div>
                    <div class="roster-team-player-info">
                        <div class="player-status">
                            <div class="player-image">
                                {{#if player_image_url}}
                                    <img src="{{player_image_url}}" class="player-image-source">
                                {{else}}
                                    <img src="/images/default-avatar.png" class="player-image-source">
                                {{/if}}
                                <img src="/images/image-hex-cover.png" class="image-overlay">
                            </div>
                            <div class="player-text">
                                <div class="player-name">Mark Benivegna</div>
                                <div class="player-status-message">Forward</div>
                            </div>
                        </div>
                    </div>
                </div>
                {{/each}}
            </div>
        </div>
        {{/each}}

Data:

$teams =    Array
(
    [0] => Array
        (
            [players] => Array
                (
                    [0] => Array
                        (
                            [id] => 123
                            [number] => 1
                            [name] => Cory Zzzzz
                            [position] => Defense
                        )

                    [1] => Array
                        (
                            [id] => 123
                            [number] => 2
                            [name] => Cory Zzzzz
                            [position] => Defense
                        )

                )

            [name] => Home
            [jersey] => dark
            [locker_room] => 
        )

    [1] => Array
        (
            [players] => Array
                (
                    [0] => Array
                        (
                            [id] => 123
                            [number] => 1
                            [name] => Mark Zzzzz
                            [position] => Forward
                        )

                    [1] => Array
                        (
                            [id] => 123
                            [number] => 2
                            [name] => Mark Zzzzz
                            [position] => Forward
                        )

                )

            [name] => Away
            [jersey] => light
            [locker_room] => 
        )

)

Nested if/else helper not working on PHP 5.2

I know PHP 5.2 is a bit old but is the version that some hosting providers (like HostGator) have installed so it cann't be left forgotten.

This code is working ok in PHP 5.4 but for some reason in a PHP 5.2 installation it throws the following error:

<b>Parse error</b>: syntax error, unexpected T_FUNCTION in <b>/.../Handlebars/Helpers.php</b> on line <b>71</b><br />

My Handlebars template is has follows:

     <div class="text-align-{{ options.alignment }} border-bottom-{{ options.style }}" style="border-width: {{ options.width }}px; border-color: {{ options.color }}">
        {{#if options.use_title_separator}}
            <div>
                {{#if options.back_to_top}}
                    <a href="" onclick="return false;">{{ options.text_label }}</a>
                {{else}}
                    {{ options.text_label }}
                {{/if}}
            </div>
        {{/if}}
    </div>

It could be great if you can help me on this.

Thanks

support for @first/@last in #each helper

in the handlebars.js reference, there is a paragraph on automatic variables available in the each context.

"The first and last steps of iteration are noted via the @FIRST and @last variables when iterating over a array. When iterating over an object only the @FIRST is available."

I don't see support for those two variables in the source, is this planed or did I miss them ?

Add registerPartial() functionality like in Handlebars.js

Is it possible to have a registerPartial() function such as in the JavaScript version? This allows you to bind a dynamic partial like main page content/body with a different file depending on the website page being requested e.g. use registerPartial("body", "contentblocks/list") when using the FileSystem loader as the partials loader and registerPartial("body", "Hello, {{name}}") for the StringLoader.

Is this stable enough to use?

Is this library in a stable enough state to start using?
It looks promising, but before I do a fork and start implementing and helping out with it, I need to know if I can actually use it.

Great stuff though! I'm sure many people would find this useful. 👍

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.