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

each cannot cross a simple array [key => value] ? #318

Open ghost opened 5 years ago

ghost commented 5 years ago

The PHP Code:

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

// The Template:
$template = <<<VAREND
{{#each table as |value key|}}
KEY: {{dump key}}
VAL: {{dump value}}
{{/each}}
VAREND;

// Helpers:
$helpers = array(
  'dump' => function ($x) {
    return var_export($x, true);
  },
);

// Partials:
$partials = array(
    'bar' => 'Yes, partial',
);

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

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

// Input Data:
$data = array(
  'table' => array(
    'foo' => 'bar'
  )
);

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

The Issue:

An array like ['key' => 'value'] cannot be cross by an each... It's work if you value is an array, but not a string...

Can you solve this ?

Krinkle commented 4 years ago

The Handlebars "each" syntax is best for iterating key-value objects in an array. That way, every key comes from your data and has a name that you can find easy:

$table = [
  [ 'a' => 'foo', 'b' => 'bar' ],
  [ 'a' => 'baz', 'b' => 'quux' ],
];
{{#each table}}
A: {{a}}
B: {{b}}
{{/each}}
$table = [
  [ 'key' => 'foo', 'value' => 'bar' ],
  [ 'key' => 'baz', 'value' => 'quux' ],
];
{{#each table}}
KEY: {{key}}
VALUE: {{value}}
{{/each}}

It is also possible to access the whole current value, with the {{.}} syntax. And the current key index, via the {{@index}} syntax.

See also http://handlebarsjs.com/builtin_helpers.html#iteration and https://zordius.github.io/HandlebarsCookbook/0019-each.html.

For example, your data can be displayed like this:

$data = array(
  'table' => array(
    'foo' => 'bar'
  )
);
{{#each table}}
KEY: {{@index}}
VAL: {{.}}
{{/each}}