Reputation: 2137
I'm coming from PHP (laravel), I'm still new to node.js and its being fun but i have some issues with using server side functions in my html view. Unlike in laravel, where i have access to some important server side functions that makes work faster by avoiding repetitions in my view, i don't seem to have access to server side functions in node.js (express). In laravel i can do these in my views:
asset('images/avatar.jpg')
config('app.name')
url('users/posts')
In laravel, my images and other files are in storage directory which is not in the public directory but using the asset() function in blade template, i can access files in storage folder.
In my current node.js app, i have a pathConfig.json file that contains my app path settings, At the server side I can access the file, how can i access the same path from my view ? I'm using express with handlebars
Upvotes: 0
Views: 340
Reputation: 2137
I've gotten exactly what i wanted using express-handlebars' custom helper... With express-handlebars, i can write my function at the server side and use it in the view.
I have a helper.js file at the server side
const url = function(link=false) {
return process.env.URL+'/'+link;
};
const anotherFunction = function() {
return 2+2;
};
module.exports = {
url : url,
anotherFunction : anotherFunction
};
App.js file
helpers = require('./helpers.js');
app.engine('.html', hbs({
extname : '.html',
defaultLayout: 'main',
helpers: helpers
}));
In my view (index.html)
<a href="{{url 'post/comments'}}"> Post comments</a>
Upvotes: 1
Reputation: 5603
create a public
directory in which you will save all your assets css, js, fonts, images
, after that you must set the static
middleware which allow express to serve file that are store in some location
var app = express()
// attaching the static middleware
app.use(express.static(path.join(__dirname, 'public')))
if you have an image test.png
store in the images
subfolder of your public directory you can access that by using http://xxxxx:port_number/test.png
Upvotes: 0