【问题标题】:Node.js - How to include a file in a vash template?Node.js - 如何在 vash 模板中包含文件?
【发布时间】:2015-09-21 18:52:27
【问题描述】:

我有一个使用 Express 和 Vash 的 Node.js 应用程序。我的布局如下所示:

layout.vash

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

MyClass 是这样定义的 ES6 类:

MyClass.js

'use strict';

class MyClass {
  constructor() {
  }

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

我的挑战是,当我包含 model.items = MyClass.LoadItems(); 行时,我的视图将不会加载。如果我注释掉该行,视图将按预期加载。我怀疑因为该行使用 ES6,所以存在一些编译问题。当我包含该行时,我在控制台窗口中看到以下错误:

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 

有没有办法让MyClasslayout.vash 中访问?如果有,怎么做?

谢谢!

【问题讨论】:

  • 我注意到的第一件事是它应该是new MyClass().LoadItems();,但你仍然缺少一些东西。我不熟悉 vash,但看起来您需要以某种方式包含 MyClass.js
  • @AnotherDev。我同意我需要包含MyClass。我不确定如何。就像我不能在 Vash 中使用 require 一样。这似乎很奇怪。我不需要new,因为该函数是静态可见的。
  • 明白了,你是怎么用 es5 做的?

标签: javascript node.js vash


【解决方案1】:

一般来说,在 express 中(就像在大多数视图引擎中一样),当您调用渲染函数时,您会在模型中传递您需要的任何属性。您可以在模型对象中传递您想要的任何内容,包括一个类(最终是一个函数 - 因此是对象):

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

【讨论】:

    猜你喜欢
    • 2014-05-16
    • 2021-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-11
    • 1970-01-01
    • 2011-07-20
    相关资源
    最近更新 更多