Jump to content

WebApps with LocalStorage and AppCache/Create an AppLSAC/Handlebars4Code

From Wikiversity

Introduction

[edit | edit source]

Handlebars4Code is a library and NPM module that extends Handlebars with Helpers for Code Generation in a specific programming language (e.g. Javascript)

Learning Tasks

[edit | edit source]

Use Cases - Javascript Template Engines

[edit | edit source]

The following use-cases guide you from standard Handlebars usage toward Handlebars4Code usage.

Basic Use Case

[edit | edit source]

Assume you have a JSON with data in it and you want to create a HTML table with data in the JSON.

{
  "person":{
    "firstname":"Anna",
    "lastname":"Almond"
  }
}

The HTML output:

<table>
  <tr>
    <td>First Name:</td>
    <td>{{person.firstname}}</td>
  </tr>
  <tr>
    <td>Last Name:</td>
    <td>{{person.lastname}}</td>
  </tr>
</table>

For this basic examples you might want to use just Handlebars directly as Javascript template.

// Define JSON
var vJSON = {
  "person":{
    "firstname":"Anna",
    "lastname":"Almond"
  }
};
// Define Template
var vTemplate = "Name: {{person.firstname}} {{person.lastname}}";
// Create Compiler
var vCompiler = Handlebars4Code.create_compiler4template(vTemplate);

// Show Output for JSON on console
console.log("Output: " + vCompiler(vJSON));

Use Case - Generation of Programming Code

[edit | edit source]

For generation of Programming code the standard markers with two brackets Template:Firstname are replaced in general by markers with 3 brackets {{{firstname}}} because the replacement by Handlebars with two brackets escapes characters like “>” by &gt;. This is for HTML output in general useful, but for generation of code with template engine the code may become syntactically incorrect due to escaping of characters

{
  "statement":{
    "type":"if",
    "codition":"a < b"
  }
}

The Code Template for Handlebars4Code would e.g. like this:

{{{statement.type}}} ( {{{statement.condition}}} ) {
  // other code
}

The replacement of {{{statement.condition}}} would provide the correct desired output

if ( a < b )

and the replacement of Template:Statement.condition would create an syntactical error of the generated code by

if ( a &gt; b ).

If you want to use Handlebars4Code for code generation use 3 brackets for encoding the variable replacement with JSON content. The same is applicable, if you create HTML-tags with

See also

[edit | edit source]