Backbone, JST, EJS: Blank values in templates-Collection of common programming errors

I have a JST–>EJS backbone template for a ‘projects’ form. Ideally, I’d like to use the same template for both creating and editing models.

At the moment, I have something such as this in the template:


That works fine so long as demo_field has a value, but if it doesn’t, the whole form fails with an uncaught referenceError.

So, what’s the most elegant way to assure variable fields return blank, instead of fail, in Backbone…or JST…or EJS?

Cheers…

  1. I’d probably make a helper, since javascript doesn’t have any nice way of doing something like field if field? in CoffeeScript.

    Throw something like this into a helper function:

    function printIfExists(field) {
      return (typeof field !== "undefined" && field !== null) ? field : '';
    }
    

    and call it in your templates. Easy as pie!

    You might also want to use the alternate function declaration:

    var printIfExists = function(field){...}
    

    I’ve been using coffeescript so long I can’t recall why… scoping issues with the former example, probably.

Originally posted 2013-11-09 22:46:42.