【问题标题】:Meteor - Coffeescript helper not fired when in the same folder as JadeMeteor - 与 Jade 位于同一文件夹时,Coffeescript 助手不会被触发
【发布时间】:2015-10-14 00:26:19
【问题描述】:

我开始在我的 Meteor 应用程序上使用 Coffeescript,虽然在包中一切正常,但在将我的 js 文件模板函数转换为 .coffee 时遇到了一些问题。

即使在我编译咖啡脚本时它似乎是正确的,但在我呈现网页时似乎并没有触发我的助手和事件。我什至在 Web 控制台上都没有收到错误消息。

我搜索了,但除了this thread,什么都找不到。

我使用 Jade、Coffeescript,我的 .coffee 和 .jade 文件位于同一个文件夹中,如下所示:

client/templates/myTemplate/myTemplate.jade

client/templates/myTemplate/myTemplate.coffee

我尝试了 _ 方法,将我的文件重命名为 .html.jade 和 js.coffee,但到目前为止没有任何效果。如果我将计算的 javascript 放在 myTemplate.js 文件中,一切正常。

有什么想法吗?

以下是代码示例:

Template.loginButton.helpers
    statusText: () ->
        console.log 'anybody there?'
        if Meteor.user() then "Déconnexion" else "Connexion"

【问题讨论】:

    标签: javascript meteor coffeescript pug template-engine


    【解决方案1】:

    Coffeescript 对缩进很敏感。如果您不熟悉使用 coffeescript,该站点 js2.coffee 非常有用。把你的代码粘贴进去,输出下面的JS,说明你已经有效地生成了一个no-op:

    Template.loginButton.helpers;
    
    ({
      statusText: function() {
        console.log('anybody there?');
        if (Meteor.user()) {
          return "Déconnexion";
        } else {
          return "Connexion";
        }
      }
    });
    

    另一方面,使用正确的缩进

    Template.loginButton.helpers
      statusText: () ->
        console.log 'anybody there?'
        if Meteor.user() then "Déconnexion" else "Connexion"
    

    你得到

    Template.loginButton.helpers({
      statusText: function() {
        console.log('anybody there?');
        if (Meteor.user()) {
          return "Déconnexion";
        } else {
          return "Connexion";
        }
      }
    });
    

    更新:既然这不是问题,请注意,如果您同时使用第三方模板系统 (jade) 和第三方 JS 转译器 (coffeescript),您需要在 JS 之前先加载模板,以确保您可以从代码中访问模板。所以无论是在你的.meteor/packages(对于一个应用程序),还是在package.js(对于一个包)中,确保jade在coffeescript之前。

    附:我是一个长期的咖啡用户,但我正在切换到 ES6,因为它具有咖啡的大部分重要特性,而没有太多的机会让你自责。此外,很难与不懂咖啡的人合作。

    【讨论】:

    • 抱歉,粘贴的文字不正确。我的代码的缩进方式和你写的一样(我也在 js2.coffee 上测试过)。
    • 确保你在 coffeescript 之前添加了jade包(否则模板可能不存在来添加帮助器)。
    • 你成功了!请编辑您的回复,以便我接受您的回答:)
    【解决方案2】:

    感谢 Andrew,我终于找到了问题所在。 结果是我通过 npm 安装了 Coffeescript,当 .coffee 位于一个包中时,这并没有造成任何问题,因为它们在任何情况下都处于加载顺序。 但是当涉及到模板和助手时,顺序很重要,我猜 npm coffeescript 库是在 .jade 模板存在之前编译和执行的,导致我的助手没有附加到任何模板。

    终于

    meteor add coffeescript
    

    并确保在 .meteor/packages 中将翡翠放在咖啡脚本之前。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-09
      相关资源
      最近更新 更多