kirbysayshi/vash

Possible to access Node.js functionality inside a template?

Closed this issue · 3 comments

While currently evaluating your (great!) engine inside a Node.js test project, I tried the following (although not sure whether I really need it) inside a .vash template file:

@{
    var fs = require('fs');

    // ...more code...
}

This results in an error message

require is not defined.

My question: Is this something that is simply not possible and/or am I totally misusing the idea of a template engine?

So, you really shouldn't need this within a template, although it can be possible. The reason why it doesn't work is because require is provided for each module in nodejs, and is not actually a global. To make this work, you could so something like:

@{ var fs = model.require('fs'); }
tpl({ require: require })

Or if you set useWith: true, you could just reference require like before.

But even though this is possible, it's probably not something you should do. Usually it's better to pass everything into the template. But maybe you're doing something super cool! In that case carry on!

Thanks a lot for helping me on this. I strongly doubt that what I'm doing is actually that cool that it needs something so unusual 😉.

Just adding a clarification for myself about what the useWith does:

This plugin configures Vash to use its useWith mode, meaning that the members of the template data are available to the razor view as the default object.

(Quote from here)