The method for calling the JavaScript EJS template library in the Node. js project, node. jsejs
As an external module, the calling method is the same as that of the mysql module.
The render function of ejs has two parameters: the first is a string and the second is an optional object. Data to be rendered, like other javascript templates, is also included in the option object.
Ejs. render (str, option); // The rendering string str is generally read by the readfile method of the nodejs file system. render (str, {data: user_data // data to be rendered });
If the str string does not contain the include tag, rendering data is correct. Otherwise, an error is returned. As mentioned earlier, my project file and nodejs installation file are not in the same root directory. To solve this problem, you must configure the filename attribute of the option parameter.
Looking at the ejs source code, we will find that ejs will use a resolveInclude function when processing the path containing include files:
function resolveInclude(name, filename) { var path = join(dirname(filename), name); var ext = extname(name); if (!ext) path += '.ejs'; return path; }
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 cannot be found.
When using dirname, you should note that the first path parameter is intercepted when the function processes the input path parameter.
The Section before '/' is used as the path name, for example:
path.dirname('/foo/bar/baz/asdf/quux') // returns '/foo/bar/baz/asdf'
To obtain the tpl directory, you can write as follows:
path.dirname('/tpl/..') // return /tpl
The complete render function can be as follows:
Ejs. render (str, {filename: path + '/tpl/..', // The template file data: user_data} is saved in the tpl file });
Articles you may be interested in:
- Node. js is suffixed with. html when the ejstemplate is used.
- Ejs v9 javascript template System
- NodeJS framework Express template view Mechanism Analysis