How to access assets / images from a view in Sails.js?

I just want to add an image to a view in my Sails project

My view file has a location

views/album/albums.ejs 

and the image is in

 assets/images/placeholder.png 

if i add this image as

 <img src="../../assets/images/placeholder.png"> 

I get this error

 GET http://localhost:1337/assets/images/placeholder.png 404 (Not Found) 

Did I miss something?

+8
html ejs
source share
5 answers

Sails uses Grunt (Gruntfile.js in the root directory of the project) to perform some tasks while raising sails. One of these tasks is to copy files from the resource directory to the .tmp / public / directory (in the development version). Therefore, if you add your file to the asset directory, you will need to restart the sails (raising sails) in order to access it from .tmp / public / (which is the public directory of the directory). It is also important to note that if u put the files directly in .tmp / public /, it will be available instantly, but the next time you raise the sails it will be deleted, since one of the tasks of Grunt is to clear this directory before copying new files. All this can be found in the sail documentation ( assets and asset-management ) and by reading Gruntfile.js in the root of your project

+14
source share
 <img src="/images/placeholder.png"> 

must work. the resource folder is equivalent to adding a folder with static middleware in the expression.

asset documentation

+8
source share

It looks like you removed grunt .

When removing the grunt hook, you must also specify the following in .sailsrc to serve your assets, otherwise all assets will be returned 404 .

 { "paths": { "public": "assets" } } 
+3
source share

I also ran into the same problem.
In sails versions 0.12.0,
I tried to show the image from the resource folder on homepage.ejs.
Then, using the bottom img tag, it solved my problem.

 <img src="/images/placeholder.png" width="30px" height="30px"> 

But since your ejs file is inside views / album / albums.ejs

I can suggest below may work

 <img src="../images/placeholder.png" width="30px" height="30px"> 

But the correct approach to ejs sail pages is:

 <img src="/images/placeholder.png" width="30px" height="30px"> 

This should also work for you.

0
source share

If your project has a tasks / sync.js file, add the following object to the files array:

 { cwd: './assets/images', src: ['**/*.*'], dest: '.tmp/public/images' } 

you need to set sail-hook-grunt and grunt-sync.

0
source share

All Articles