Search code examples
javascriptnode.jsvash

Node.js - How to include a file in a vash template?


I have a Node.js app that uses Express and Vash. I have a layout that looks like this:

layout.vash

<!DOCTYPE html>
<html>
@{
  model.items = MyClass.LoadItems();
}
  <head>
  </head>
  <body>
  </body>
</html>

MyClass is an ES6 class defined like this:

MyClass.js

'use strict';

class MyClass {
  constructor() {
  }

  static LoadItems() {
    var items = [];
    // ...
    return items;
  }
}

My challenge is, my view will not load when I include the model.items = MyClass.LoadItems(); line. If I comment out the line, the view loads as expected. I suspect that because the line uses ES6, there is some compilation problem. When I include the line, I see the following error in the console window:

ERROR:
ReferenceError: Problem while rendering template at line 2, character 16.
Original message: Problem while rendering template at line 2, character 16.
Original message: MyClass is not defined.
Context: 

     1 | <!DOCTYPE html>
  >  2 | <html lang="en">
     3 | @{   
     4 |     model.items = MyClass.LoadItems();
     5 |     var navItemsB = [];

.
Context: 

     1 | @html.extend('layout', function(model){
  >  2 |     @html.block('content', function(model){            
     3 |       <div>
     4 |         <div 

Is there a way to make MyClass accessible within layout.vash? If so, how?

Thanks!


Solution

  • Generally speaking, in express (like in most view engines) you pass whatever properties you need in the model when you call the render function. You can pass whatever you want in your model object, including a class (Which in the end is a function - hence object):

    app.get('/', function (req, res) {
      res.render('layout', { MyClass });
    });