Sails.js - How to inject a js file to a specific route?

Js Lim picture Js Lim · Mar 1, 2014 · Viewed 8.1k times · Source

For example, I have a page /locations/map which I need to include Google Map library, and include a .js file (e.g. location.js) specifically for this page only.

I want to inject these 2 files to after <!--SCRIPTS END--> this line

Is it possible to do this?

NOTE: I was using Sails.js v0.10

Answer

sgress454 picture sgress454 · Mar 3, 2014

Sails uses ejs-locals in its view rendering, so you can accomplish what you want with blocks.

In your layout.ejs file, underneath the <!--SCRIPTS END-->, add (for example):

<%- blocks.localScripts %>

Then in the view you're serving at /locations/map, call the block with your script tag, for example:

<% block('localScripts', '<script src="https://maps.googleapis.com/maps/api/js"></script>') %>

As an alternative, you could put the <!--SCRIPTS--> and <!--SCRIPTS END--> tags in the <head> of your layout, and then add your view-specific scripts directly into your view rather than using blocks. This is a fine option if you don't mind waiting for those linked scripts to load before your page content is displayed.