【问题标题】:How to remove unnecessary blank spaces from compiled Eco template如何从编译的生态模板中删除不必要的空格
【发布时间】:2012-05-18 07:26:26
【问题描述】:

假设我有这个简单但相当嵌套的 Eco 模板:

<div class="example">
  <% for thing, i in @things: %>
    <div class="nested">
      <% if i % 2 == 0: %>
        This block is fairly nested.
      <% end %>
    </div>
  <% end %>
</div>

编译成JS的结果是:

function(__obj) {
  // ... A couple of auxiliary functions ...
  (function() {
    (function() {
      var i, thing, _i, _len, _ref;

      __out.push('<div class="example">\n  ');

      _ref = this.things;
      for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
        thing = _ref[i];
        __out.push('\n    <div class="nested">\n      ');
        if (i % 2 === 0) {
          __out.push('\n        This block is fairly nested.\n      ');
        }
        __out.push('\n    </div>\n  ');
      }

      __out.push('\n</div>\n');

    }).call(this);

  }).call(__obj);
  __obj.safe = __objSafe, __obj.escape = __escape;
  return __out.join('');
}

现在,这个函数(作为 JS 提供给客户端进行客户端渲染)在字符串上包含一些不必要的空格,例如 ...

`'\n        This block is fairly nested.\n      '`

... 不能被 JS 压缩器移除,因为它们不是 JS 空格(但在渲染时会变成 HTML 空格)。我了解 Eco 以这种方式编译模板以保持它们的输出很好地缩进,这在开发环境中很酷,但在生产环境中则不然:D

有没有办法从eco.precompile 输出中删除这些不必要的空格?

顺便说一句,我正在使用 Sprockets 来编译、连接和提供这些资产。

【问题讨论】:

  • 我没有使用过 Eco,也没有直接的环境来尝试任何东西。你能看看在&lt;!-- --&gt; 中包含不需要的空格是否有帮助吗?
  • 感谢@AtesGoral 的建议,但不幸的是,这无济于事,因为在 JS 输出中看到的空格是因为模板中使用了缩进(我编辑了我的问题,评论说)。在添加不必要的 HTML 注释块之前,我宁愿删除源模板的缩进,但这远非理想的解决方案(可能有一种方法可以在 .eco -> .js 编译时删除它们)。
  • 如果 Eco 支持 XML cmets,它可能仍然有效。我将发布我的意思作为答案。
  • 一种选择是破解/覆盖github.com/sstephenson/eco/blob/master/src/util.coffee 并使inspectString 通过trim 管道。

标签: javascript coffeescript sprockets eco


【解决方案1】:

如果 Eco 支持 XML cmets,这可能会有所帮助:

<div class="example">
  <% for thing, i in @things: %><!--
    --><div class="nested"><!--
      --><% if i % 2 == 0: %>
        This block is fairly nested.
      <% end %>
    </div>
  <% end %>
</div>

不过,你必须在这种丑陋或放弃缩进的丑陋之间做出选择。

【讨论】:

  • HTML cmets 也包含在 JS 输出中以及空白处。 Eco 借鉴了 ERB 的注释语法:''。那些 cmets 不会出现在 JS 输出中,但是用 cmets 替换缩进对我来说是不行的,这不是我想要的 =D
【解决方案2】:

如果你这样写呢

<div class="example">
  <% for thing, i in @things: %>
    <div class="nested"><%= "fairly nested" if i % 2 is 0 %></div>
  <% end %>
</div>

按照 ECO 模板 README 中的建议,在关于空格的注释下。

【讨论】:

    猜你喜欢
    • 2016-06-16
    • 2020-04-21
    • 2014-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多