Saturday, September 23, 2017

How to Embed a JavaScript Script in a Handlebars Template

While working on the next generation of ThePresidentsOftheUnitedStates.com, a site I'm working on with my 10yr old daughter, we needed to add a little bit of JavaScript in the template to add the ordinal suffix to a number (e.g., "3rd President").

It's easy enough to do by registering a Handlebars helper and calling it with "{{{nth number}}}". Here's the code in context:

<header>
<h1>The Presidents Of The United States</h1>
</header>
<script>
Handlebars.registerHelper('nth', function(n) {
  return new Handlebars.SafeString(
    ["st","nd","rd"][((n+90)%100-10)%10-1]||"th"
  );
});
</script>
<script id="entry-template" type="text/x-handlebars-template">
{{#each presidents}}
<div class="row" itemscope itemtype="http://schema.org/Person">
  <div class="col-sm-4 centered" > <!-- left panel -->
  <h2 class="name" itemprop="name">{{fname}} {{mname}} {{lname}}</h2>
  <p class="ordinal">{{number}}{{{nth number}}} President of the United States</p>
Special thanks to Tomas Langkaas from stackoverflow for the "nth" algorithm in JS.

No comments: