Handlebars

RAD Theme Engine comes with handlebars-php as a dependancy, here's how to use and configure it.

Usage

Firstly, create a new template file in the tpl/ folder. For this example we’ll name the file home-title.tpl. For a complete guide on how to use Handlebars templating syntax, check out the handlebars-php repository.

tpl/home-title.tpl
Welcome to <span style="color:red">{{title}}</span>!
A simple handlebars template

Rendering

To render this we need to call the file and supply it with the data it needs. Since I only want to use this template on my home page, I’ll add this code to home.php:

home.php
echo site()->render("home-title",[
"title" => get_bloginfo("name")
]);
Rendering a block of HTML

Recall we added a function in functions.php to expose our Site object to all the pages, and that’s what we’re using here.

Here’s what we see on the homepage now:

Wow! What a site!

Loops

Iterating through collections with handlebars is easy, just pass an array into your model and use the #each helper.

home.php
echo site()->render("people-list.tpl",[
"people" => [
[
"first" => "Gabin",
"last" => "Ábel"
],
[
"first" => "Koji",
"last" => "Hallþóra"
],
[
"first" => "Carmi",
"last" => "Surendra"
],
]
]);
tpl/people-list.tpl
{{#each people}}
<b>{{first}}</b> {{last}}
{{/each}}
A simple loop in handlebars

Conditions

With handlebars' #if helper, blocks will not render if the condition returns false, null, '', or [].

home.php
echo site()->render("people-list.tpl",[
"people" => []
]);
tpl/people-list.tpl
{{#if people}}
First Person: {{people.0.first}}
{{#else}}
There are no people!
{{/if}}
An if/else statement in handlebars

See more about handlebars on the docs.

Template File Extension

By default Handlebars templates are files that end with .tpl and exist inside the tpl/ folder in the theme root.

config.php
"handlebars" => [
"template-extension" => "tpl"
]