Caseblocks Logo

How to Write a HTML Template

How to Write a HTML Template

Templates are found by clicking the Admin menu and clicking Email Templates.  They can be used to generate most text based formats, for example: HTML, Plain Text, XML, JSON.

In this example, we’ll generate an Invoice from an order.  First thing to do is to write a lifecycle function against the order case type, this way the order will be loaded in by default.  Next look at the related line items and load these in, we’ll need these for the invoice.  Once you have all of these, we need to create a new javascript object that has the order, and the line items in it, for example:

const invoiceData = {
  "order_reference": "Order-1234",
  "order_date": "2017-04-27T19:28:54.544Z",
  "line_items": [
       "line_item_reference": "Order-1234-1",
       "product_name": "Widget 52",
       "quantity": 4,
       "unit_cost": 23.4

This has the information we need for a very simple invoice, obviously if you want more info then add to this structure.

const renderTemplate = (category, name, data, auth_token) => {
  postData = Object.assign(data, {current_user:options.current_user})
  url =""+category+"/"+name+"?auth_token="+auth_token
  return fetch(url, { method:"POST", body:JSON.stringify(postData), headers: { 'Content-Type':'application/json' }}).then((res) =>res.text()))

renderTemplate(“order”, “invoice”, invoiceData, “your-auth-token-goes-here”)

And thats the script taken care of, now we need to create the template.  We use a templating engine called Handlebars ( to merge the data you supply from the script to the template above.  You can read more in here, we will be using the basics in this walk through.  In the template you write your HTML or text as normal, and where you want to insert a variable, you use 2 ‘curly braces’ to surround the name of the value you want to insert.  For Example order_date from above;

<div class="order_date">{{order_date}}</div>

Now we want to loop around the line items, there are a number of functions in handlebars, I would encourage you to look at the readme in the link above for the full set.

  <tr><th>Product</th><th>Quantity</th><th>Unit Cost</th><th>Cost</th></tr>
  {{#each line_item}}

Notice that product_name isn’t line_items.product_name, this is because within the #each block the scope moves to the current item in the array that your are looping over.

While editing the template, you can supply a sample object that you want to supply to the template, this helps to turn around the template quicker, you can also load case data from a previously viewed case if you wish also.