Jade <code>renderFile</code> - 羡辙杂俎
2015.12.19 19:02:09
Jade renderFile

One thing you need to keep in mind when using Jade is that it is a template that renders HTML on the server side. In some cases, we need to use the template for contents loaded with AJAX requests. Although a more popular solution would be returning JSON data and having it rendered on the client side using frameworks like Angular.js, here we choose to render it on the server side using Jade.

To do this, you should first install jade with npm, and require it where needed. Jade provides a function called renderFile to render with a Jade file.

But it gets confusing when setting the path of the Jade file. Say, if we have a jade file called hello.jade under views directory

h1 Hello, #{name}.

and a js file under app/routes directory

var jade = require('jade');

    'views/hello.jade', {
        name: 'Xianzhe'
    }, function(err, html) {
        if (err) {
            res.status(500).send('Fail to render.');
        } else {

Note that the file path has to be views/hello.jade, rather than hello.jade or ../../views/hello.jade.

The final result would be

<h1>Hello, Xianzhe.</h1>


Creative Commons License
Every blog post in this site by Wenli Zhang is licensed under a CC 3.0 License, based on a work at Github. You can see the source code of this blog site at github.com/Ovilia/blog.


comments powered by Disqus