【问题标题】:Jade templating "each" function returns empty object玉模板“每个”函数返回空对象
【发布时间】:2011-01-11 02:36:13
【问题描述】:

我遇到了一个困扰我好几天的错误。我对 Node 和 Jade 模板系统还很陌生,所以请耐心等待:我希望通过以下方式添加样式表:

App.js (Express):

app.get('/', loadUser, function(req, res) {
 var User = req.user;
 // console.log(User.groups[2]);
 // var groups = User.groups.split(',');
 // OK DUh. This only gets called when the client has the script Socket.IO
 // and client runs socket.connect()

 getMessages(User, function(messages) {

  var locals = {
   scripts: [
    'https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js',
    'index.js'
   ],

   stylesheets: [
    'index.css'
   ],

   user : User,
   messages: messages
  };

  console.log('ok');

  res.render('app.jade', {locals : locals});

 });

});

在 layout.jade(使用 app.jade 执行)中,我有:

!!! 5
html
 head
  title UI
  link(rel='stylesheet', href = 'stylesheets/reset.css')
  link(rel='stylesheet', href = 'stylesheets/layout.css')
  - var stylesheets = stylesheets || [];
            #{stylesheets}
  - each stylesheet in stylesheets
   - if(stylesheet.indexOf('http') >= 0)
    link(rel='stylesheet', href = stylesheet)
   - else
    link(rel='stylesheet', href = "stylesheets/"+stylesheet )

还有更多...我一直遇到同样的错误:

9. ' - if(stylesheet.indexOf(\'http') >= 0)'

Object function () {
  var o = {}, i, l = this.length, r = [];
  for(i=0; i
  for(i in o) r.push(o[i]);
  return r;
} has no method 'indexOf'

现在.. 问题是这个确切的模板可以在另一个传递完全相同变量的应用程序中工作:我非常感谢你们对这个棘手问题的任何建议!

谢谢! 马特·穆勒

【问题讨论】:

    标签: templates views node.js pug


    【解决方案1】:

    所以这是你的问题...

    在这一行:

    res.render('app.jade', {locals : locals});

    你传入的是 locals ==> locals,这是一个哈希(好吧,所以我是一个 PERL 人,我认为 JS 称它们为“关联数组”)

    所以现在在你的玉模板里面我们有一行:

     - var stylesheets = stylesheets || []; 

    在 JADE 中,您已经定义了变量“locals”,但其他所有内容都隐藏在其中,因此没有定义变量“stylesheets”(而是定义了 locals.stylesheets)。所以这行代码将变量“stylesheets”设置为“[]”

    所以这里是我必须推测的地方。 “indexOf”是 Array 对象的一个​​方法。也许在 JADE 中构建的数组没有这个方法,而在 node.js 中构建的数组有这个方法。这可以解释为什么您在尝试调用“stylesheets.indexOf(...)”时会出错

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-21
      • 2014-02-11
      • 2011-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-23
      • 2010-12-18
      相关资源
      最近更新 更多