The test file
function a(obj){
    let str = ' '
    with(obj){
        str += ` 
         
       
       
       Document  
            arr.forEach(item= > {
                str += `<li></li>`
            })
        str += ` `
    }
    return str
    
}
console.log(a({arr: [1.2.3]}))
Copy the code

Running results:

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta  name="viewport" content="width=device-width, Initial - scale = 1.0 "> < title > Document < / title > < / head > < body > < li > < / li > < li > < / li > < li > < / li > < / body > < / HTML >Copy the code

1,with determines that the default this refers to 2, and a function runs to implement the concatenation of STR

The template HTML file

This is the HTML template

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Document</title>
</head>
<body>
    {{ name }} {{ age }}

    {% arr.forEach(item => { %}
        <li>{{item}}</li>%} {%})</body>
</html>
Copy the code
The template. Js file

This is the parsing HTML file generation template

const ejs = require('ejs') // Third party module

const path = require('path')/ / path module

const fs = require('fs')// File module

// Parse the function
const renderFile = (filePath,obj,cb) = > {
    // Fetch file module fs reads HTML template
    fs.readFile(filePath,'utf8'.function(err,html){
        if(err){
            return cb(err,html)
        }
        // The {{name}} template in the HTML is matched with the re and replaced with the HTML
        html = html.replace(/\{\{([^}]+)\}\}/g.function(){
            let key = arguments[1].trim()
            return '${' + key +'} '
        })
        // Compare the header of the file with the a function of the test file above
        // Include the with syntax
        let head = `let str = ''; \r\n with(obj){\r\n`
        head += 'str +=`'
        // Replace {% item %} in the HTML string with item
        html = html.replace(/\{\%([^%]+)\%\}/g.function(){
            return '`\r\n'+arguments[1] +'\r\n str += `\r\n'
        })
        let tail = '`}\r\n return str; '
        // Use new Function to convert a string to a Function
        let fn = new Function('obj',head + html + tail)
        // Execute the call callback and pass in the fn Function fn is the Function generated with new Function
        cb(err,fn(obj))
        // console.log(html)
    })
}

renderFile(path.resolve(__dirname,'template.html'), {name:'eee'.age:'234'.arr: [1.3.4.5]},function(err,data){

    console.log(data,'rrrrrrr')})Copy the code