TAGS :Viewed: 15 - Published at: a few seconds ago

[ sails js template jst.js error can't find variable _ ]

I'm new to programming and learning JavaScript and Sails JS. I do love it so far but ran into a problem which I don't understand. Forgive me if I'm using the wrong terminology, I have no programming background.

I run on Sails v0.12.1 (clean install) and on OSX (if this matters)

In /assets/templates I have created a template file called 'testTemplate.ejs'. Which only contains a h3 tag with simple text:

<h3>This is the template</h3>

In my /assets/js/app.js I have a simple jQuery 'call' to inset the template in my clientside page:


So far so good. My app works fine on all views etc but trows an error when it reaches this point. The error is telling me that it can't find variable '_' which is located in /jst.js at the first __t (line 4):

this["JST"] = this["JST"] || {};
this["JST"]["assets/templates/addUser.ejs"] = function(obj) {
    obj || (obj = {});
    var __t, __p = '', __e = _.escape;
    with (obj) {
        __p += '<h3>Dit is de template</h3>';
    return __p

I've tried to install underscore.js with the command:

npm install underscore --save

But that didn't make a difference. I've also tried to use html instead of ejs for the template (changing the pipeline as well).

I have no clue anymore why I'm getting this error:

ReferenceError: Can't find variable: _

or how I should/could fix it.

Can anyone please help me?

Answer 1

Thanks to @Armfoot I've found the solution.

Installing the underscore.js through npm didn't work as expected. But when I download the underscore.js file manually and place it in the /assets/js/ directory then lift sails the error is gone and the template is loaded correctly.

Must be my missing knowledge to search for an answer well over two days which is so simple to solve. Again thanks Armfoot for pointing me in the correct direction.

Answer 2

Perhaps underscore.js was not properly imported or referenced previously, try to find in the loaded code something similar to this line:

<script src="YOURPATH/underscore.js"></script>

Or try to add this before you use underscore:

$.getScript("https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js", function( data, textStatus, jqxhr ) {
  console.log( data ); // Data returned
  console.log( textStatus ); // Success
  console.log( jqxhr.status ); // 200
  console.log( "Load was performed." );

And according to their documentation, you need to add a string parameter in the escape function. E.g.:

_.escape('Curly, Larry & Moe');
=> "Curly, Larry &amp; Moe"