Recently thinking of writing something practical tools, is accidentally came into contact with this noun template engine, so special check, BELIEVE that in this three framework (😜 may be two big framework) popular when, how much contact, just do not know that this is the credit of template engine.


This article is very simple, just a brief introduction, see the related documentation for more apis


Touched the template

The most obvious feature of a template engine is the use of curly braces{{}}(But not limited to{{}}, or some other particular symbol)keyValue, render itkeyThe correspondingvalue

Templates in VUE

Template syntax is clearly used in VUE, and their documentation is explicit

Vue.js uses htML-based template syntax that allows developers to declaratively bind DOM to the data of the underlying Vue instance. All vue.js templates are valid HTML, so they can be parsed by standards-compliant browsers and HTML parsers. On the underlying implementation, Vue compiles templates into virtual DOM rendering functions. Combined with a responsive system, Vue can intelligently calculate how many components need to be rerendered and minimize DOM operations. If you are familiar with the virtual DOM and prefer the raw power of JavaScript, you can also write the render function without templates, using the optional JSX syntax.

As we can see above, we just put {{message}} in the tag, but the rendering is crude and does correspond to the value of message in the data declaration below. Of course, Vue does a lot of stuff in between, and diff algorithms and stuff like that, but we’re not going to get into diff algorithms today, Just looking at the template engine in the front end

Also, there is an implementation in VUE — a single-file component

Basically, a.vue file is parsed by webpack’s loader and finally displayed. We just have to look at the implementation of this curly brace, which is the same thing as above

Templates in LoDash

Template ([string= “], [options={}])

The template in LoDash looks a little different from vue’s, doesn’t it? It uses something like <%= %> to wrap variable names, so I said at the beginning that it’s not limited to curly braces like {{}}

Other templates

Back when I first got into the front end, as I mentioned in my previous blog, I used backbone.js, which is once again a template method in underscore. Js, which is also a library (or framework) that changes page content through templates, and there are also templates on the back end before the front and back ends are separated.

What is a template

What is a template? My understanding is that I like a set of templates in advance, and then according to different data, change the data in the template, and the template structure does not change. How say understand some, is now a lot of outsource website, they will write well in advance many sets of website, all kinds of, and then according to the different needs of customers, change the content inside, prior written this website even template, and then change the company name, contact phone number and pictures and some other things, can quickly output


Of course, my goal today is not to talk about what a template is, just to get a sense of what it is, and I’m going to talk about this template engine, rightHandlebars.jsBecause the tool I’m going to write is going to use this, so I’m just going to talk about how to use it, and hopefully it will be a little bit helpful for those of you who use this thing in the future, right

The text start

<script type="text/template"> 和 <template>

That’s the nature of these two tags. Browsers don’t directly parse the tags inside them

Browsers ignore these tags, which allows us to put anything in there that can be retrieved for later use in the template library, but the

Handlebars.js (template engine library)

Handlebars. Js gives you the awesome ability to easily build semantic templates. Handlebars. Js is compatible with Mustache

Handlebars.js is kind of an extension of Mustache. Js, so it’s ok to use this. So how do we use it? To look down

Easiest to use


      
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>A template engine</title>
  <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://cdn.bootcss.com/handlebars.js/4.1.2/handlebars.min.js"></script>
</head>
<body>
  <div id="root"></div>

  <template id="template">
    <p>Name: {{name}}</p>
    <p>Age: {{age}}</p>
  </template>

  <script>
    $(function() {
      var data = {
        name: 'Front End Battle Five'.age: 16
      };
      var root = $('#root'); // To get the root node, change the label of the content
      var htmlNode = $("#template").html(); // Get the label content
      var templateWithoutData = Handlebars.compile(htmlNode); // Create a template with no data
      var templateWithData = templateWithoutData(data); // Upload data to a template without data
      root.html(templateWithData); // Add the template with the data to the page
    })
  </script>
</body>
</html>
Copy the code

The result of the above code run is

This is the simplest implementation, rendering the data in the data to the page, the following is a small switch page function I wrote


      
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>A template engine</title>
  <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://cdn.bootcss.com/handlebars.js/4.1.2/handlebars.min.js"></script>
</head>
<body>
  <div>
    <p>This is navigation</p>
    <button data-place="one">Really new town</button>
    <button data-place="two">Japan,</button>
    <button data-place="three">Japan forest</button>
  </div>
  <div id="content"></div>

  <template id="one">
    <h1>{{ name }}</h1>
    <p>I was the first page</p>
  </template>

  <template id="two">
    <h1>{{ name }}</h1>
    <p>I'm the second page</p>
  </template>

  <template id="three">
    <h1>{{ name }}</h1>
    <p>I'm the third page</p>
  </template>

  <script>
    var one = { name: 'True New Town' };
    var two = { name: 'Joban city' };
    var three = { name: 'Changpan Forest' };
    $(function () {
      var content = $('#content');
      $('button').on('click'.function () {
        var target = $(this).attr('data-place');
        var htmlNode = $(The '#' + target).html();
        var templateWithoutData = Handlebars.compile(htmlNode);
        var templateWithData;
        switch(target) {
          case 'one':
            templateWithData = templateWithoutData(one);
            break;
          case 'two':
            templateWithData = templateWithoutData(two);
            break;
          case 'three':
            templateWithData = templateWithoutData(three);
            break; } content.html(templateWithData); })})</script>
</body>
</html>
Copy the code

helper

There’s nothing in the documentation that explains what a helper is, but it’s just some built-in syntax that we can use, and we can customize, but we won’t cover it here, okay

if helper

So that’s where we can write some if else logic in the template, to see what’s hidden, right

<div id="root"></div>

<template id="template">
    {{#if job}}
    <p>Name: {{name}}</p>
    <p>Age: {{age}}</p>
    <p>Job: {{job}}</p>
    {{else}}
    <p>No job yet</p>
    {{/if}}
</template>

<script>
$(function() {
  var data = {
    name: 'Front End Battle Five'.age: 20.job: 'Front-end development'
  };
  var root = $('#root'); // To get the root node, change the label of the content
  var htmlNode = $("#template").html(); // Get the label content
  var templateWithoutData = Handlebars.compile(htmlNode); // Create a template with no data
  var templateWithData = templateWithoutData(data); // Upload data to a template without data
  root.html(templateWithData); // Add the template with the data to the page
})
</script>
Copy the code

By following the code above, the job in data has a value and I can show it in the final render

So let’s say I delete job

var data = {
    name: 'Front End Battle Five'.age: 20.job: ' '
  };
Copy the code

{{else}}

Comments in templates

How do we write comments in the template, just look at them

<template id="template">
    {{#if job}}
    <p>Name: {{name}}</p>
    <p>Age: {{age}}</p>
    <p>Job: {{job}}</p>
    {{else}}
    <! -- I am a comment. I am a comment.{{! I'm a comment I'm a comment}} {{! }}<p>No job yet</p>
    {{/if}}
</template>
Copy the code

We know that in HTML, comments are
is written this way, yes, but this will be displayed in HTML, so how do we write comments to not display in the page, that is my code to write {{! }} and {{! — -}}

conclusion

Handlebars.js supports the template language, and if else is enough for me to write my own tool. The documentation for Handlebars. In fact, this thing is not difficult to use, if you write a template engine, that is awesome people


I’m a front end warrior, a front end elementary school.