Summary of Handlebars, a front-end template engine

I. escape of Handlebars template

1. template
Escape, output HTML string when {}} is used
When {{}}} is used, html is output without escaping (identifying HTML tag attributes)

2.Helpers medium
When return '< span style ='color: Red' > safety string < / span > ', escape and output HTML string
When return new handlebars.safe string ('< span style ='color: Red' > safety string < / span > '), do not escape and output HTML

In the template:

<script id="entry-template" type="text/template">
    <div>
        <h2>{{title}}</h2>
        <h3>Escape:{{content}}</h3>
        <h3>No escape:{{{content}}}</h3>
    </div>
</script>
<script type="text/javascript">
    var source = $("#entry-template").html();
    var template = Handlebars.compile(source);
    //Define the data to display
    var context = {
        title: "Test escape content",
        content: "<span style='color:red'>Please see my font color</span>"};
    var html = template(context);
    $("body").html(html);
</script>
Design sketch

In Helpers:

/**
 * Split string, comma separated by default, get the path of image and return img tag, no escape
 */
Handlebars.registerHelper('splitBySymbol', function(tag) {
    var ret = "",symbolTag=",";
    if(tag!= null && tag!=""){
        var tags = tag.split(symbolTag);
        if(tags!=null && tags.length > 0){
            for(var i=0, j=tags.length; i<j; i++) {
                ret = ret + "<img src='"+tags[i]+"'/>";
            }
            return new Handlebars.SafeString(ret);
        }
    }else{
        return "";
    }
    return new Handlebars.SafeString(ret);
});

2. Customize Helpers to escape json string and get the value of corresponding key

    /**
     * Custom Helper converts json string and gets corresponding value
     * getJsonValueByKey: Function name
     * str: json Character string
     * key: To get the json object key name
     * */
    Handlebars.registerHelper("getJsonValueByKey",function(str,key) {
        if(str==null || str=="") {
            return str;
        }
        if(typeof str === "string"){
            return JSON.parse(str)[key];
        }
        return "";
    });

Example code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="//code.jquery.com/jquery-1.8.2.min.js"></script>
    <script src="//cdn.bootcss.com/handlebars.js/4.0.6/handlebars.js"></script>
    <title>handlebars</title>
</head>
<body>
</body>
<script id="entry-template" type="text/template">
    <div>
        <h2>{{title}}</h2>
        <h3>Today is
            <span>{{getJsonValueByKey date 'year'}}year</span>
            <span>{{getJsonValueByKey date 'month'}}month</span>
            <span>{{getJsonValueByKey date 'day'}}day</span>
        </h3>
    </div>
</script>
<script type="text/javascript">
     /**
     * Custom Helper converts json string and gets corresponding value
     * getJsonValueByKey: Function name
     * str: json Character string
     * key: To get the json object key name
     * */
    Handlebars.registerHelper("getJsonValueByKey",function(str,key) {
        if(str==null || str=="") {
            return str;
        }
        if(typeof str === "string"){
            return JSON.parse(str)[key];
        }
        return "";
    });

    var source = $("#entry-template").html();
    var template = Handlebars.compile(source);
    //Define the data to display
    var context = {
        title: "custom Helpers Transferred meaning json String and get the corresponding key Of value",
        date: '{"year":"2018","month":"12","day":"22"}'
    };
    var html = template(context);
    $("body").html(html);
</script>
</html>

The renderings are as follows:



3. User defined Helpers to judge whether two variables are equal

Handlebars.registerHelper('eq', function(v1, v2, opts) {
    if(v1 == v2){
        return opts.fn(this);
   }else{
        /*Reverse and execute the else statement in the template*/
        return opts.inverse(this);
  }
});

Example code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="//code.jquery.com/jquery-1.8.2.min.js"></script>
    <script src="//cdn.bootcss.com/handlebars.js/4.0.6/handlebars.js"></script>
    <title>handlebars</title>
</head>
<body>
</body>
<script id="entry-template" type="text/template">
    <h3>
        {{#eq num 12}}
             //This is the month of {{this.num}}
        {{else}}
            //This is not the month of {{this.num}}}
        {{/eq}}
    </h3>
</script>
<script type="text/javascript">
    Handlebars.registerHelper('eq', function(v1, v2, opts) {
        if(v1 == v2){
            return opts.fn(this);
        }else{
            /*Reverse and execute the else statement in the template*/
            return opts.inverse(this);
        }
    });
    var source = $("#entry-template").html();
    var template = Handlebars.compile(source);
    //Define the data to display
    var context = {
        num:12
    };
    var html = template(context);
    $("body").html(html);
</script>
</html>

Design sketch

4. Use. To access the attribute and.. / to access the parent attribute
Example code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="//code.jquery.com/jquery-1.8.2.min.js"></script>
    <script src="//cdn.bootcss.com/handlebars.js/4.0.6/handlebars.js"></script>
    <title>handlebars</title>
</head>
<body>
</body>
<script id="entry-template" type="text/template">
    {{#each author}}
        <h1>Title:{{../title}}</h1>
        <h2>Full name:{{this.name}}</h2>
        <h3>Age:{{this.age}}</h3>
    {{/each}}
</script>
<script type="text/javascript">
    var source = $("#entry-template").html();
    var template = Handlebars.compile(source);
    //Define the data to display
    var context = {
        title: "This is title",
        id:20,
        author: [{
            name: "Wang Yi Bo",
            age: 20
        }],
        content: "This is content"
    }
    var html = template(context);
    $("body").html(html);
</script>
</html>

Technical blog of the original author: https://www.jianshu.com/u/ac4daaeecdfe
After 95, there is a front-end girl who loves reading and making friends. Record the problems encountered in work here, hoping to bring a little help to everyone you see.
Welcome to leave a message.

Tags: Handlebars JSON JQuery Javascript

Posted on Mon, 02 Dec 2019 05:30:37 -0500 by George Botley