Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to write a page template engine with javascript

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article focuses on "how to use javascript to write a page template engine", interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to write a page template engine with javascript.

At first I thought something like this:

Var TemplateEngine = function (tpl, data) {/ / magic here...} var template ='

Hello, my name is. I\'m years old.

'; console.log (TemplateEngine (template, {name: "Krasimir", age: 29}))

A simple function, the input is our template and data object, the output is also easy for you to think of, like this:

Hello, my name is Krasimir. Ichimm 29 years old.

The * * step is to find the template parameters and replace them with the specific data passed to the engine. I decided to use regular expressions to do this. But I'm not good at this, so if you don't write well, you're welcome to spray it at any time.

Var re = /] +)?% > / g

This regular expression captures all fragments that end in. The parameter g (global) at the end indicates that there is not only one match, but all matching fragments. There are many ways to use regular expressions in Javascript. What we need is an array based on regular expressions that contains all the strings, which is exactly what exec does.

Var re = /] +)?% > / g; var match = re.exec (tpl)

If we print out the variable match with console.log, we will see:

["," name ", index: 21, input:"

Hello, my name is. I\'m years old.

"]

However, we can see that the returned array contains only * matches. We need to wrap the above logic in a while loop so that we can get all the matches.

Var re = /] +)?% > / g; while (match = re.exec (tpl)) {console.log (match);}

If you run the code above, you will see it and it has been printed out.

Next, here comes the interesting part. After identifying the matches in the template, we replace them with the actual data passed to the function. The easiest way is to use the replace function. We can write like this:

Var TemplateEngine = function (tpl, data) {var re = /] +?% > / g; while (match = re.exec (tpl)) {tpl = tpl.replace (match [0], data [match [1]])} return tpl;}

All right, so we can run, but it's not good enough. Here we use a simple object to pass data in the way of data ["property"], but in reality we probably need more complex nested objects. So we modified the data object a little bit:

{name: "Krasimir Tsonev", profile: {age: 29}}

However, if you write like this directly, you can't run, because if you use it in the template, the code will be replaced with data ['profile.age'], and the result will be undefined. In this way, we can't simply use the replace function, but in other ways. If you can use Javascript code directly in between, you can evaluate the incoming data directly, like the following:

Var template ='

Hello, my name is. I\'m years old.

'

You may wonder, how did this happen? Here John uses the syntax of new Function to create a function based on a string. Let's take a look at an example:

Var fn = new Function ("arg", "console.log (arg + 1);"); fn (2); / / outputs 3

Fn is a real function. It takes one parameter, and the function body is console.log (arg + 1);. The above code is equivalent to the following code:

Var fn = function (arg) {console.log (arg + 1);} fn (2); / / outputs 3

In this way, we can construct a function based on the string, including its parameters and function body. That's what we want! But don't worry, before we construct the function, let's take a look at what the function body looks like. According to the previous idea, the template engine should eventually return a compiled template. Using the previous template string as an example, the return should look like this:

Return "

Hello, my name is "+ this.name +". I\ m "+ this.profile.age +" years old.

"

Of course, in the actual template engine, we would split the template into small pieces of text and meaningful Javascript code. You may have seen me using simple string concatenation to achieve the desired effect, but this is not 100% in line with our requirements. Since consumers are likely to pass more complex Javascript code, we need another loop here, as follows:

Var template ='My skills:' +'

If you use string concatenation, the code should look like this:

Return'My skills:' + for (var index in this.skills) {+''+ this.skills [index] +''+}

Of course, this code can not run directly, running will make mistakes. So I used the logic written in John's article to put all the strings in an array and put them together in the program's *.

Var r = []; r.push ('My skills:'); for (var index in this.skills) {r.push (''); r.push (this.skills [index]); r.push ('');} return r.join ('')

The next step is to collect different lines of code in the template for generating functions. Through the methods described earlier, we can know which placeholders are in the template and where they are located. So, depending on an auxiliary variable (cursor, cursor), we can get the desired result.

Var TemplateEngine = function (tpl, data) {var re = /] +?% > / g, code = 'var r = [];\ nFor, cursor = 0; var add = function (line) {code + =' r.push ("'+ line.replace (/" / g,'\ ") +');\ n' } while (match = re.exec (tpl)) {add (tpl.slice (cursor, match.index)); add (match [1]); cursor = match.index + match [0] .length;} add (tpl.substr (cursor, tpl.length-cursor)); code + = 'return r.join (");'; / /

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report