I use LightnCandy\LightnCandy to template handlebars in PHP. I want to print some key/value pair on my template (if you have better, thanks to show me :) ).
I've try to get key value by :
- Classic method
{{#each my_table as |val key|}}
- Testing method
{{#each my_table as |val|}}
and get the key by@key
- By
@index
/@key
andthis
with{{#each my_table}}
My layout.hbs :
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
<title>Title</title>
</head>
<body>
<main role="main">
{{> page}}
</main>
</body>
</html>
My my_page.hbs :
{{dump my_table}}
{{#each my_table as |val key|}}
<article role="article">
@KEY [ {{dump @key}} ]
@INDEX [ {{dump @index}} ]
THIS [ {{dump this}} ]
VAL [ {{dump val}} ]
KEY [ {{dump key}} ]
</article>
{{/each}}
My PHP render:
// Get HBS file first
$hbs_content = file_get_contents('my_page.hbs');
if(empty($hbs_content)) throw new \Exception('HBS file not found: "my_page.hbs"');
// Render temp file
$renderFile = 'render.php';
// Get layout file
$layout = file_get_contents('layout.hbs');
if(false===$layout) throw new \Exception('Cannot read layout file "'.$layout.'".');
// Compile layout with hbs_content
$pageContent = LightnCandy::compile($layout, array(
'helpers' => array(
'dump' => function($x) { return var_export($x, true); }
),
'flags' => LightnCandy::FLAG_ELSE|LightnCandy::FLAG_ADVARNAME|LightnCandy::FLAG_SPVARS|LightnCandy::FLAG_ERROR_EXCEPTION,
'partials' => array(
'page' => $hbs_content
)
));
// Save the compiled PHP code into a php file
if(!file_put_contents($renderFile, '<?php '.$pageContent.' ?>')) throw new \Exception('Cannot write render file.');
// Get the render function from the php file
$renderer = include($renderFile);
// Save content
echo $renderer(array(
'my_table' => array(
'key1' => 'value1',
'key2' => 'value2',
'key3' => 'value3',
)
));
exit();
My HTML output:
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
<title>Title</title>
</head>
<body>
<main role="main">
array (
'key1' => 'value1',
'key2' => 'value2',
'key3' => 'value3',
)
<article role="article">
@KEY [ 'key1' ]
@INDEX [ 0 ]
THIS [ NULL ]
VAL [ NULL ]
KEY [ NULL ]
</article>
<article role="article">
@KEY [ 'key2' ]
@INDEX [ 1 ]
THIS [ NULL ]
VAL [ NULL ]
KEY [ NULL ]
</article>
<article role="article">
@KEY [ 'key3' ]
@INDEX [ 2 ]
THIS [ NULL ]
VAL [ NULL ]
KEY [ NULL ]
</article>
</main>
</body>
</html>
Expected output:
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
<title>Title</title>
</head>
<body>
<main role="main">
array (
'key1' => 'value1',
'key2' => 'value2',
'key3' => 'value3',
)
<article role="article">
@KEY [ 'key1' ]
@INDEX [ 0 ]
THIS [ value1 ]
VAL [ value1 ]
KEY [ key1 ]
</article>
<article role="article">
@KEY [ 'key2' ]
@INDEX [ 1 ]
THIS [ value2 ]
VAL [ value2 ]
KEY [ key2 ]
</article>
<article role="article">
@KEY [ 'key3' ]
@INDEX [ 2 ]
THIS [ value3 ]
VAL [ value3 ]
KEY [ key3 ]
</article>
</main>
</body>
</html>
So what I miss ?