Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

why EXPRESS+EJS template can CALL CONFIG without send it when rendering?

why EXPRESS+EJS template can CALL CONFIG without send it when rendering?

Problem

I'm learning node.js with express and ejs template. While I'm learning some code I found that they could call config in template without sending it as a variable when rendering.

here is a tiny tiny project as a "todo" program,

in its views/layout.html, I found

But in controllers/todo.js

I see

var config = require('../config');
...
res.render('index', {todos: rows});

obviously it doesn't send config to ejs, though todo.js required config at first.

so why the ejs renderer can call config while rendering?

TIA

Problem courtesy of: Nano WANG

Solution

It uses app.helpers, which exposes data to the view.

Example:

app.helpers({foo: "bar"});

is equivalent to doing:

res.render("index", {foo: "bar"});

In every call to render.

Edit: There is also app.dynamicHelpers, which lets you use stuff on req and res as well:

app.dynamicHelpers({
  foo: function(req, res) {
    return req.session.foo;
  }
});

I recommend a read-through of the Express guide, it's quite short and gives you an overview of what's available in Express.

Solution courtesy of: Linus Gustav Larsson Thiel

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

why EXPRESS+EJS template can CALL CONFIG without send it when rendering?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×