renatoargh renatoargh - 7 months ago 45
Node.js Question

How to prevent underscore.js templates to create undesired blank lines?

I am creating a generator using Yeoman, which in turn uses underscore.js templates.

In a given file I have this code:

<% _.each(requires, function(require) { %>
<% if(require.shouldApply) { %>
<%= _.camelize( %> = require('<%= %>'),
<% } %>
<% }); %>
mongoose = require('mongoose'),
Schema = mongoose.Schema;

Given that
sometimes is false I don't want a blank line to be produced.

So for example, for the input
requires: [{shouldApply: false, name: 'zoo'}, {shouldApply: false, name: 'foo'}, {shouldApply: true, name: 'bar'}]
I get this:

zoo = require('zoo'), //note that the line below is blank

bar = require('bar'), //I don't want the blank line above
mongoose = require('mongoose'),
Schema = mongoose.Schema;

Does anyone know how to prevent underscore.js templates to create these undesired blank lines?


In JSP we sometimes use the (annoying) practice of extending the template-tag onto the next line to prevent this.

It's not ideal for readability, but it does solve the 'unwanted newline' problem.

For example:

<% if(require.shouldApply) { 
%><%= _.camelize( %> = require('<%= %>'), 
<% } %>

In JSP we also have trimDirectiveWhitespaces and similar options -- which aren't perfect, but do help. Your templating system may also have something like this.