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.
Welcome to <span style="color:red">{{title}}</span>!
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
:
echo site()->render("home-title",[ "title" => get_bloginfo("name")]);
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.
echo site()->render("people-list.tpl",[ "people" => [ [ "first" => "Gabin", "last" => "Ábel" ], [ "first" => "Koji", "last" => "Hallþóra" ], [ "first" => "Carmi", "last" => "Surendra" ], ]]);
{{#each people}} <b>{{first}}</b> {{last}}{{/each}}
Conditions
With handlebars' #if
helper, blocks will not render if the condition returns false
, null
, ''
, or []
.
echo site()->render("people-list.tpl",[ "people" => []]);
{{#if people}} First Person: {{people.0.first}}{{#else}} There are no people!{{/if}}
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.
"handlebars" => [ "template-extension" => "tpl"]