I am new to Sails.js
I am trying to use the assets/templates feature in sails to render data client side but I cannot seem to find any working example.
I am looking for the native Sails solution, without angular or other frameworks. Just load .JST templates from assets/templates and populate them using jQuery
Can anyone reference a working example of using client-side templates in
sails.js?
The documentation is really lacking with this one. However, I managed to get the client-side templates working in Sails 0.12.4 with the following steps:
1. Prerequisites
By default installation, you should already have a file
views/homepage.ejswith a section for the templates:Now, by running
$ sails lift, templates underassets/templates/are compiled into a javascript filejst.jswhich is then automatically inserted intoviews/homepage.ejsbetween the template section comment tags. However, we first need a template!2. EJS Template
Write a template file, say
assets/templates/example.ejs:There is one problem. By default, Sails compiles only templates ending with
*.html. This does not make sense because the template file is clearly not HTML and also because the server-side templates underviews/already have extension.ejs. To change that, replace the following lines intasks/pipeline.js:with
This enables our
example.ejsto be compiled into thejst.jsas a javascript function.3. Define _
This is not enough. The compiled javascript in
jst.jsdepends on Underscore or alternatively Lodash. Without_in the client's namespace, executing the template function will throw an error.To import this on the client-side, download your version of choice and place it under
assets/js/dependencies/. For example the minified Lodash core seems to be sufficient. During nextsails lift, a new script tag for the file will be automatically inserted intohomepage.ejs, ultimately putting_into the namespace.4. Rendering the template
Run
$ sails liftand browse to the homepage at localhost:1337 by default. Thejst.jshas created the template function atwindow.JST['assets/templates/example.ejs'].To test it in action, open the developer console, and type:
This should return you the string
<h1>Hello</h1>. This string you now want to insert somewhere into the document. Let us say you store it into a variablepiece. You could use jQuery$('#target').html(piece)or good olddocument.getElementById('target').innerHTML = piece. Anyway, as the result, the rendered string is now inserted into the page under #target element.