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 // 需要渲染的数据 });
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; }
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'
To get the tpl directory, you can write like this:
path.dirname('/tpl/..') // return /tpl
The complete render function can be like this:
ejs.render(str,{ filename : path + '/tpl/..', //tpl文件中保存的是模版文件 data: user_data });