Skip to content

Instantly share code, notes, and snippets.

  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save michaelphipps/c5db7418835e837950dcc34bb757256d to your computer and use it in GitHub Desktop.
How to pass data to partials in Handlebars.php

How to pass data to partials in Handlebars.php

The way data is passed in partials in salesforce/handlebars-php isn't the same as it is over at handlebars.js

Inspired by this issue

In this gist, we have a dataset of names that we want to display on a page. We are using a partial to format the display of the names to avoid writing repetitive code.

[
    "names"=>[
        "boys" => [
            ["name"=>"Liam"],
            ["name"=>"Noah"],
            ["name"=>"William"]
        ],
        "girls" => [
            ["name"=>"Olivia"],
            ["name"=>"Emma"],
            ["name"=>"Ava"]
        ]
    ]
]

Pay attention to the use of the this in name_list.partial.

Output of this gist is:

<p>Boys Names</p>
<ul>
        <li>Liam</li>
        <li>Noah</li>
        <li>William</li>
</ul>

<p>Girls Names</p>
<ul>
        <li>Olivia</li>
        <li>Emma</li>
        <li>Ava</li>
</ul>
<p>Boys Names</p>
{{> name_list names.boys}}
<p>Girls Names</p>
{{> name_list names.girls}}
<ul>
{{#each this}}
<li>{{name}}</li>
{{/each}}
</ul>
<?php
use Handlebars\Handlebars;
use Handlebars\Loader\FilesystemLoader;
# Set the template files
$templatesDir = __DIR__."/templates";
$templatesLoader = new FilesystemLoader($templatesDir,
[
"extension" => "tpl"
]
);
# Set the partial files
$partialsDir = __DIR__."/templates";
$partialsLoader = new FilesystemLoader($partialsDir,
[
"extension" => "partial"
]
);
# Instantiate Handlebars
$handlebars = new Handlebars([
"loader" => $templatesLoader,
"partials_loader" => $partialsLoader
]);
# Render the template
echo $handlebars->render("main", [
"names"=>[
"boys" => [
["name"=>"Liam"],
["name"=>"Noah"],
["name"=>"William"]
],
"girls" => [
["name"=>"Olivia"],
["name"=>"Emma"],
["name"=>"Ava"]
]
]
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment