XaminProject / handlebars.php

Handlebars processor for php
331 stars 134 forks source link

Patch for arrays that contain only one elements #66

Closed jslegers closed 10 years ago

jslegers commented 10 years ago

For arrays that contain only one element, (array_keys($tmp) == range(0, count($tmp) - 1) always returns true.

(array_keys($tmp) === range(0, count($tmp) - 1) works as expected.

My local test environment = Linux Mint + PHP 5.4.

JustBlackBird commented 10 years ago

Can you provide a test case for the problem? It seems that each helper works as expected without the patch.

JustBlackBird commented 10 years ago

Sorry, @jslegers is right.

The problem takes place on the following dataset:

$data = array('test_key' => 'one');

with the following template:

{{#each data}}{{@key}}{{/each}}

The expected result is test_key but the real result is an empty string.

jslegers commented 10 years ago

@JustBlackBird :

The problem applies to all associative arrays that contain only one element.

My use case :

$data = array(
    'contacts' => json_decode($contacts, true)
);

Here, the value {{@key}} is not defined where it should be contacts.

It only occurs for associative arrays that have only one element.

So, take for example the following array.

$data = array(
    'contacts' => json_decode($contacts, true),
    'address' => json_decode($address, true)
);

Here, the value {{@key}} is contacts where it should be contacts.

The patch solves this problem and provides the value contacts in both cases.

For arrays with numeric keys only, the behavior remains unaltered (= {{@key}} is not defined in both cases).

everplays commented 10 years ago

Thanks guys.

jslegers commented 10 years ago

@everplays :

No problem. I needed that bugfix for my own project, so why not share it?! ;)

I am currently experimenting with advanced sub-templating techniques and (in parallel) different ways to pass complex dynamic data to a helper as flexible as possible. I'm willing to contribute some of my work to this project in case you guys are interested.

I created a seperate issue for this, which you can find at https://github.com/XaminProject/handlebars.php/issues/68. Let me know if you're interested and (in case you are interested) which of the sugested syntaxes you prefer.