Node.js project calls JavaScript's EJS template library methods

  • 2021-01-25 07:10:47
  • OfStack

As an external module, the method called is the same as the mysql module, so I won't go into details here.

The render function takes two arguments. 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 contained in the option object


ejs.render(str,option); 
//  Render string  str 1 A is through nodejs filesystem readfile Methods read  
ejs.render(str,{ 
  data : user_data //  The data to be rendered  
}); 

When the str string does not contain the include tag, rendering the data is fine; otherwise, an error will be reported. As I mentioned earlier, my project files are not in the same root directory as the nodejs installation files. Resolving this problem requires configuring the filename property of the option parameter.

If you look at the ejs source code, you can see that there is one resolveInclude function used by ejs when handling 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 an argument to the dirname function. As the core module of nodejs, path.dirname() always returns path relative to the installation path of nodejs. If you do not specify the filename value, the file will not be found
When using ES34en, you should be aware that the function truncates the first path parameter when it is passed in
The part before '/' is used as the path name for example:


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

To get the tpl directory, write:


path.dirname('/tpl/..') // return /tpl 

The full ES43en function would look like this:


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


Related articles: