renatoargh renatoargh - 4 months ago 16
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:

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


Given that
require.shouldApply
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:

var
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?

Answer

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.name) %> = require('<%= require.name %>'), 
<% } %>

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.

Comments