How to remove unnecessary blank spaces from compiled Eco template

670 Views Asked by At

Supose i have this simple but fairly nested Eco template:

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

When compiled to JS the result is:

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('');
}

Now, this function (which is served as JS to the client to do client-side rendering) includes some unnecessary blanks spaces on strings, like ...

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

... that cannot be removed by a JS compressor because they are not JS blank space (but become HTML blank space when rendered). I understand Eco compiles the templates this way to keep their output nicely indented, which is cool in a development environment, but not so much on a production one :D

Is there a way to remove this unnecessary blank spaces from the eco.precompile output?

BTW, i'm using Sprockets to compile, concatenate and serve these assets.

2

There are 2 best solutions below

1
On

If Eco honors XML comments, this might help:

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

Though, you would have to make a choice between this ugliness or the ugliness of giving up indentation.

0
On

What if you write it like this

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

as suggested in ECO templates README, under a note about whitespace.