The provided JavaScript/TypeScript code defines a simple template engine named TemplateEngine. This engine allows the dynamic generation of content by combining a template string with data. Here's a breakdown of how it works:
-
reg: Detects template tags enclosed in<% ... %>in the template string. -
reExp: Detects conditions (if,else,for, etc.) and loops in the template.
- Initializes a
codevariable with the string "var r=[];\n", which will be used to build the JavaScript code.
-
Defines an
addfunction to add HTML chunks to thecodevariable in JavaScript syntax. -
Handles both JavaScript code (if detected by
reExp) and regular HTML.
-
Iterates through the template using regular expressions (
reg) to find and process template tags. -
For each match, it adds the preceding HTML chunk and the matched JavaScript code to the
codevariable.
-
Adds the remaining HTML chunk after the last template tag to the
codevariable. -
Appends a line to join the contents of
codeand return it as a string.
-
Outputs the final JavaScript code to the console for inspection.
-
Uses
new Functionto create a JavaScript function from the generated code and immediately applies it to the provided data object.
-
Defines an example template using
<% ... %>tags for dynamic content. -
Calls the
TemplateEnginefunction with the template and a data object. -
Outputs the result to the console.
Example input:
const temp: string = `
<h1>
hello my name is <%this.name%>, i am
<%for(let x in this.age){%>
<%x%>
<%}%>
years old
</h1>`;
console.log(
tempEngine(temp, {
name: "feranmi",
age: [20, 10, 30],
})
);output
var r=[];
r.push("<h1>hello my name is ")
r.push(this.name);
r.push(", i am")
for(let x in this.age){"
r.push("x");
}
r.push("years old </h1>");
outout: hello my name is feranmi, i am 20 10 30 years old