Node.js the method of calling JavaScript's Ejs Template Library in a project _node.js

Source: Internet
Author: User

As an external module, the method invoked is the same as the MySQL module, and is no longer to repeat.

Ejs's render function has two arguments. The first is a string, the second is an optional object, and the data that needs to be rendered as other JavaScript templates is included in the option object

Ejs.render (str,option); 
Render string str typically reads the 
ejs.render (str,{ 
  data:user_data//required render data}) through the ReadFile method of the Nodejs file system 
; 

When an include tag is not included in the STR string, rendering data is not problematic, and conversely, an error is encountered. I've already mentioned that my project file and the Nodejs installation file are not in the same root directory. To resolve this issue, configure the filename attribute of the option parameter.

Looking at the Ejs source, you will find that Ejs uses a resolveinclude function when dealing with the path to the include include file:

function resolveinclude (name, filename) { 
 var path = join (dirname (filename), name); 
 var ext = extname (name); 
 if (!ext) path = '. Ejs '; 
 return path; 
} 

FileName is precisely the parameter of the DirName function, as the path.dirname () of the Nodejs core module, the path returned is always relative to the Nodejs installation path, and if no filename value is specified, the file cannot be found
When using dirname, it should be noted that when a function processes an incoming path parameter, it intercepts the first
The section before '/' as a path name for example:

Path.dirname ('/foo/bar/baz/asdf/quux ') 
//returns 
'/FOO/BAR/BAZ/ASDF ' 

To obtain the TPL directory you can write this:

Path.dirname ('/tpl/. ')//RETURN/TPL 

The complete render function can be this way:

Ejs.render (str,{ 
  filename:path + '/tpl/... ',//TPL file is saved in template file 
  data:user_data 
}); 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.