handlebars-php icon indicating copy to clipboard operation
handlebars-php copied to clipboard

Model in partial template

Open azjol opened this issue 5 years ago • 2 comments

Hello, I cannot send data into partial template (ver. 2.3.0)

{{> partials/_head title="Header title" }}

Is it possible or Am I doing something wrong? Thank you

azjol avatar Sep 07 '20 15:09 azjol

Hi @azjol

tldr;

Your partial reference in the main template should look like this

{{> _head data }}

Your partial would contain this:

<h1>{{title}}</h1>

and you pass the data via render() this way

$handlebars->render("main", [
    "data"=>[
        "title"=>"Header title"
        ]
    ]
);

Read on for more detail. Sorry it is long. This info is missing or isn't clear in the current docs.

Partial Naming

You can't refer to directories in the partial's name. You can only use the name of the file.

If you do want to put partials in a different directory to templates, you need to set your code up like this:

# assuming you've already set up $templatesLoader ;)
...
# Set the partial files
$partialsDir = __DIR__."/templates/partials";
$partialsLoader = new FilesystemLoader($partialsDir, [
        "extension" => "partial"
    ]
);

# Instantiate Handlebars
$handlebars = new Handlebars([
    "loader" => $templatesLoader,
    "partials_loader" => $partialsLoader,
    
]);
...

Note: I prefer to keep my partials in the same folder as templates, so I give them the extension .partial

Passing Data

The way you pass data to partials works differently in this php library than it does in handlebars.js.

Assuming the following setup:

main.tpl

{{> _head}}

_head.partial

<h1>{{title}}</h1>

If you load the template using

$handlebars->render("main", ["title"=>"Header title"]);

the output will be:

<h1>Header title</h1>

Because the partial is aware of the data available to the parent.

The moment you pass data to the partial, it only knows about the data passed to it. If you changed main.tpl to:

{{> _head title}}

the output will be:

<h1></h1>

title actually contains the string "Header title" and not an array containing title so there is no {{title}} value it can insert.

There is a special {{this}} reference that contains the context (the data the partial is aware of) that can come in handy! If you change _head.partial to:

<h1>{{this}}</h1>

the output will be:

<h1>Header title</h1>

To prevent this answer getting too much longer, I've created this gist How to pass data to partials in Handlebars.php with a better use case for the {{this}}.

michaelphipps avatar Oct 23 '20 07:10 michaelphipps

Thanks @michaelphipps this is excellent documentation that and would be a great addition to the README. Would you mind spinning up a PR to add this in?

sam-osborne-tech avatar Dec 03 '20 18:12 sam-osborne-tech