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) specif
Scott's answer is the proper way to insert non-global JS into a specific view. Just a little comment, though: the block
call from the view should not have the dash. It should be as follows:
<% block('localScripts', '') %>
Both calls will work, but using the dash makes the insertion twice; once the view is loaded and previous to the layout render, and then once again when the view is inserted in the rendered base layout. This leads not only to inserting/running unnecessarily twice the same code but also to errors that break your JS code if the inserted script depends on libraries that you have in your base layout (e.g. jQuery, Backbone).
EJS interprets the magic <%-
as "insert unescaped". So, -I guess- what this is doing is calling the block()
function, which returns our HTML tag. This is replaced where the magic was called but also is executing the
block()
function inside of it, which is executing the layout block localScripts
replacement.
On the other hand, <%
means "instruction". I.e., just run this JS piece of code, which is not echoed to the view where is called.