This is the second day of my participation in Gwen Challenge

Preface:

As a front-end person, whether we have an in-depth understanding of ECMAScript (JavaScript) determines how far we can go, especially today, but we often use frameworks such as Vue and React for view rendering. Frameworks encapsulate too much of the bottom layer, so it’s time to study the source code of the bottom layer. To see how each of these frames turns the data into a view, we’re going to implement a Mustache template engine from scratch day two, so I decided to get down to business today and take a look at how Mustache template engine works.

First of all, to build a wheel, we must be clear about our purpose:

  1. Learn to use a wheel;
  2. Understand the principle of wheels;
  3. Build your own wheel

Step by step to improve yourself

The official installation of the installation tutorial here is not too much introduction, also suggest that you have the ability to see more official documents.

Introduction to Mustache Template Engine

  • A template engine is the most elegant solution for turning data into views

  • Mustache official git: github.com/janl/mustac…

  • Mustache is “Mustache” because the embedded tag {{}} looks a lot like Mustache. That’s right, the syntax for {{}} is also used by Vue, which is why we learn Mustache

  • Mustache is one of the oldest template engine libraries, much older than Vue, and its underlying implementation mechanism is very creative and exciting at the time, providing a new idea for the development of subsequent template engines

Basic use of Mustache Template engine

  • Variable rendering

    {{ name }}

    Variables are written inside {{}}. Is this the same as the Vue template? That’s right, because Mustache comes from the Vue template engine.

    <body>
        <div id="container"></div>
    
        <script src="jslib/mustache.js"></script>
        <script>
            var templateStr = '< H1 > I bought a {{thing}}, good {{mood}} ah ';
    
            var data = {
                thing: Huawei Mobile phone.mood: 'happy'
            };
    
            var domStr = Mustache.render(templateStr, data);
            
            var container = document.getElementById('container');
            container.innerHTML = domStr;
        </script>
    </body>
    Copy the code

    Render the view as follows

    ! [image-20210602225031019](/Users/chenuvi/Library/Application Support/typora-user-images/image-20210602225031019.png)

  • Array of loop objects

    <body>
        <div id="container"></div><! -- -- -- > templates<script type="text/template" id="mytemplate">
            <ul>
                {{#arr}}
                    <li>
                        <div class="hd">{{name}}Basic information about</div>    
                        <div class="bd">
                            <p>Name:{{name}}</p>    
                            <p>Gender:{{sex}}</p>    
                            <p>Age:{{age}}</p>    
                        </div>
                    </li>
                {{/arr}}
            </ul>
        </script>
    
        <script src="jslib/mustache.js"></script>
        <script>
            var templateStr = document.getElementById('mytemplate').innerHTML;
    
            var data = {
                arr: [{"name": "Xiao Ming"."age": 12."sex": "Male" },
                    { "name": "Little red"."age": 11."sex": "Female" },
                    { "name": "Small strong"."age": 13."sex": "Male"}};// Will view the string
            var domStr = Mustache.render(templateStr, data);
            var container = document.getElementById('container');
            container.innerHTML = domStr;
        </script>
    </body>
    
    Copy the code

    ! [image-20210602225127790](/Users/chenuvi/Library/Application Support/typora-user-images/image-20210602225127790.png)

  • Nesting of arrays

    <body>
        <div id="container"></div>
    
        <script src="jslib/mustache.js"></script>
        <script>
            var templateStr = ` < ul > < li > {{# arr}} {{name}} hobby is: < ol > < li > {{# hobbies}} {{...}} < / li > {{/ hobbies}} < / ol > < / li > {{/ arr}} < / ul > `;
    
            var data = {
                arr: [{'name': 'Ming'.'age': 12.'hobbies': ['swimming'.'badminton'] {},'name': 'little red'.'age': 11.'hobbies': ['programming'.'Write an essay'.'Read the paper'] {},'name': 'jack'.'age': 13.'hobbies': ['Play billiards']]}},var domStr = Mustache.render(templateStr, data);
            
            var container = document.getElementById('container');
            container.innerHTML = domStr;
        </script>
    </body>
    Copy the code

    ! [image-20210602225215957](/Users/chenuvi/Library/Application Support/typora-user-images/image-20210602225215957.png)

You can see that Mustache is pretty powerful here, rendering variables, arrays, and nested arrays flexibly, so how does he do it?

2. A sneak peek at the Mustache engine

We download Mustache locally, modify it, and log it here:

So regardless of what the tokens are, what do you see in the console when you render an array of tokens

Tokens now form an array of tokens and mark the variables that we want to render. The 0th element of each number has “text”, “#” and “name” tokens, which represent the types of variables. “Text” represents text, “#” represents array, “Name” represents a common variable.

3. How the Mustache engine works

What is the tokens

  • Tokens are nested arrays of JS, which are, in plain English, JS representations of template strings

  • It is the originator of “abstract syntax tree”, “virtual node” and so on

For example

I bought a {{thing}}, good {{mood}} ah

The above template string is then converted into a Token array after Mustache is picked up, which becomes the Tokes array shown below.

Tokens: Each item in this array is a token that together makes up tokens

The mechanics of Mustache Mustache

Mustache mustache focuses on two things:

  1. Compile the template strings into tokens
  2. Tokens are combined with data and parsed into DOM strings

Finally, the DOM string is inserted into the corresponding view container for rendering.

conclusion

Well, today’s content is over here, thank you 🙏 everyone to watch, if you like, please give me a thumbs-up!

Author: chenuvi

Email address: [email protected]