What is a templating engine?

A template engine is the most elegant way to turn data into a view. Other ways of changing views of data have appeared in history

  • Pure DOM method
  • In order to improve the readability of the DOM structure, we use the join method of the array (turn the array into a string). Note that the parameter “” of the join can not be omitted, otherwise the obtained STR string will be separated by commas
  • Es6 template string (‘ ‘)

Mustache basic grammar

Mustache is the word for mustache because the embedded mark {{}} is very much like a mustache. The {{}} syntax is also used by vue. Note that you can’t write expressions in {{}} the way you do in vue. Using Mustache requires the introduction of Mustache, which can be introduced directly through CDN. You then generate the DOM template with Mustache. Render (templateStr, data)

Several render cases

Render object array

<div id="box"></div>
Copy the code
/ / data
const data = {
  arr: [{name: 'Jay'.age: 18
    },
    {
      name: 'Bin'.age: 20}}]/ / dom template
const templateStr = ` < ul > {{# arr}} < li > < div > the basic information of the {{name}} < / div > < div > < p > {{name}} < / p > < p > {{age}} < / p > < / div > < / li > {{/ arr}} < / ul > `
// The introduction of Mustache through CDN creates mustache
const domStr = Mustache.render(templateStr, data)
const box = document.getElementById('box')
box.innerHTML = domStr
Copy the code

Render a simple array

/ / data
const data = {
  arr: ['red'.'orange'.'yellow']}/ / dom template
const templateStr = ` 
      
    {{#arr}}
  • {{.}}
  • {{/arr}}
`
Copy the code

Each item in the array is represented by. In the template

Boolean value

If m is true, div will be mounted to the DOM tree, otherwise it will not

/ / data
const data = {
  m: true
}
/ / dom template
const templateStr = ` 
      
{{#m}}
aaa
{{/m}}
`
Copy the code

One More Thing

Before ES6, where was the DOM template when there was no ‘ ‘?

You can write the DOM template in the

This is a study note on the principles behind {{}} used in vUE. Follow up with Mustache Engine 02 or mustache Engine 03