Preface:

Chapter 3 of building a Mustache Template engine from scratch.

The principle of checking

We talked a little bit about how Mustache works, right? We convert the Template string into an array of tokens. I’m going to talk a little bit about how that works.

First, review our previous chestnuts:

<body>
    <div id="container"></div>
    <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

Process interpretation:

I bought a {{thing}}, ok {{mood}} oh

At this point Mustache finds {{and stops and puts

I buy a collection as the first token, mark it “text”, store it in tokens array 0, then go to Thing mark it “name”, store it in tokens array 1, Then Mustache finds}} pause; Go through the template string, find “text”, store tokens 2, pause {{, then find “name”, store tokens 3, Then Mustache finds}} pauses and ends up depositing ah

. As shown in the figure:

Analytical way

The previous data is just a simple variable, what if it is a complex nested array, object? For example, our data looks like this:

/ var/data data = {students: [{' name ':' xiao Ming ', 'hobbies: [' programming', 'swimming']}, {' name ':' red ', 'hobbies: [' reading 'and' play ', 'draw']}, {' name ':' small strong ', 'hobbies: [' exercise']}};Copy the code
  1. Scattered tokens form nested arrays

  1. Tokens are combined with data and parsed into DOM strings.

  1. Finally, insert the DOM string into the view tag to render.

Implementation process has a lot of clever design, you can view the source code!

Finally, paste the source link: gitee.com/chenuvi/m-m…