Skip to content

Instantly share code, notes, and snippets.

@mattheu
Created March 14, 2016 14:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattheu/dd90e6beb77e55a96ede to your computer and use it in GitHub Desktop.
Save mattheu/dd90e6beb77e55a96ede to your computer and use it in GitHub Desktop.
Templating

Using handlebars in WordPress.

One approach we have taken is to mix handlebars templates into the standard WordPress theme templates.

We have a template function available in WordPress render_hbs_template which will render a handlebars template using the data provided. Under the hood render_hbs_template uses this PHP class https://github.com/zordius/lightncandy

The render function handles some logic around caching the compiled templates to improve performance using these.

Here is an example single.php template of how this might be used to render an article.


<?php get_header(); ?>
<div class="main">
  
  <?php 
    
  while ( have_posts() ) {
    the_post();
    // Something to handle formatting the data.
    render_hbs_template( ‘article’, $data  ); 
  }
    
  ?>
  
</div>
  
<?php get_footer(); ?>

The general page structure is still managed through standard WordPress templates, but individular atomic/modular components are all handled through handlebars.

Why I like this approach

  • The general theme is still pretty familiar to most WordPress developers.
  • This is pretty similar to how Timber works, only with handlebars instead of Twig.
  • The structural page HTML is less likely to change
  • Handlebars becomes a tool we can use on top of the standard WordPress.
  • We don't have to re-invent too much. EG how to handle WP hooks in header/footer.
  • We still get much of the benefit of handlebars for modular components

Helpers

Handlebars is great for security as it escapes by defualt to prevent XSS vulnerabilities. WordPress requires you to explicity use the escaping helper functions. However WordPress has some extra contextually aware escaping functions. For example - esc_attr escape string for use in an attribute. Or esc_url to ensure it is a valid URL.

We can actually bring these to handlebars by registering these helpers. You could use them like so.

<a class="{{ esc_att class }}" href="{{ esc_url url }}">{{ esc_html text }}</a>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment