Home > Web Front-end > JS Tutorial > Method of calling JavaScript's EJS template library in Node.js project_node.js

Method of calling JavaScript's EJS template library in Node.js project_node.js

WBOY
Release: 2016-05-16 15:11:02
Original
1486 people have browsed it

As an external module, the calling method is the same as that of the mysql module and will not be described again.

The render function of ejs has two parameters. The first is a string, and the second is an optional object. Like other JavaScript templates, the data that needs to be rendered is also included in the option object

ejs.render(str,option); 
// 渲染字符串 str 一般是通过nodejs文件系统的readfile方法读取 
ejs.render(str,{ 
  data : user_data // 需要渲染的数据 
}); 
Copy after login

When the str string does not contain the include tag, there is no problem with rendering the data. Otherwise, an error will be reported. As mentioned before, my project file and the nodejs installation file are not in the same root directory. To solve this problem, you need to configure the filename attribute of the option parameter.

Looking at the ejs source code, you will find that ejs uses a resolveInclude function when processing the path of the include file:

function resolveInclude(name, filename) { 
 var path = join(dirname(filename), name); 
 var ext = extname(name); 
 if (!ext) path += '.ejs'; 
 return path; 
} 
Copy after login

filename is the parameter of the dirname function. As the path.dirname() of the nodejs core module, the returned path is always relative to the nodejs installation path. If the filename value is not specified, the file will not be found
When using dirname, you should note that the first
will be intercepted when the function processes the incoming path parameters. The part before '/' is used as the path name. For example:

path.dirname('/foo/bar/baz/asdf/quux') 
// returns 
'/foo/bar/baz/asdf' 
Copy after login

To get the tpl directory, you can write like this:

path.dirname('/tpl/..') // return /tpl 
Copy after login

The complete render function can be like this:

ejs.render(str,{ 
  filename : path + '/tpl/..', //tpl文件中保存的是模版文件 
  data: user_data 
}); 

Copy after login

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template