Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Express.js / Jade / Pug

Hi,

I'm going through the express.js course and been learning about Jade (pug) but I'm kinda confused cause with my index.pug template I used pug.renderFile() to get the app working, but with the post.pug I had to use pug.compileFile() even though I had to use the response.send() in both cases to make it work - any ideas why?

app.get("/", function(request, response) {
    var indexPage = pug.renderFile(__dirname + "/templates/index.pug");
    response.send(indexPage);
});

app.get("/blog/:title?", function(request, response) {
    var title = request.params.title;
    if (title === undefined) {
        response.status(503);
        response.send("This page is under construction!");
    } else {
        var blogPage = pug.compileFile(__dirname + "/templates/post.pug");
        var post = posts[title];
        response.send(blogPage({ post: post }));
    }
});

1 Answer

https://pugjs.org/api/reference.html

compileFile() says it "Compile a Pug template from a file to a function which can be rendered multiple times with different locals." [emphasis mine] So compileFile will prep it so it's half-way rendered but won't substitute the values for placeholders just yet.

        var blogPage = pug.compileFile(__dirname + "/templates/post.pug");
        var post = posts[title];
        response.send(blogPage({ post: post }));

// should be the same as:

        var post = posts[title];
        var blogPage = pug.renderFile(__dirname + "/templates/post.pug", { post: post });
        response.send(blogPage);

// but you should be able to set the view engine then call response.render() directly and 
// let express handle calling pug
app.set('view engine', 'pug');
app.set('views', __dirname + '/templates');

// ...
        var post = posts[title];
        response.render('post', { post: post });

This makes sence, thank you very much :-)