0

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!

tcigrand
  • 2,357
  • 2
  • 14
  • 24
user70192
  • 13,786
  • 51
  • 160
  • 240
  • First thing I noticed is it should be `new MyClass().LoadItems();`, but you're still missing something. I'm not familiar with vash, but it looks like you need to include `MyClass.js` somehow. – tcigrand Sep 21 '15 at 20:04
  • @AnotherDev. I agree I need to include `MyClass`. I'm not sure how though. Its like I can't use a `require` in Vash. Which seems odd. I do not need `new` though as the function is statically visible. – user70192 Sep 21 '15 at 20:35
  • Gotcha, how do you do it with es5? – tcigrand Sep 21 '15 at 20:39

1 Answers1

0

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 });
});
Amit
  • 45,440
  • 9
  • 78
  • 110