Where to access and store EJS Helpers - SailsJS

て烟熏妆下的殇ゞ 提交于 2019-12-01 04:13:35

问题


Well,

SailJS's default templateing engine is EJS (Embedded Javascript)

But I cannot seem to find the place where we can create our own helpers and stuff.

So, do you know where to access & store EJS helpers/stuff?


回答1:


solved: https://github.com/balderdashy/sails/issues/2162#issuecomment-55866731

config/http.js

module.exports.http = {
  // ...
  locals: {
    filters: {
      formatDate: function(date) { }
    }
  }
}

config/bootstrap.js

_.extend(sails.hooks.http.app.locals, sails.config.http.locals);

At some view...

views/test.ejs

<%=: created | formatDate %>



回答2:


You should create file in ./config with name anyname.js and write some EJS helper like these code:

var moment = require('moment');
var ejs = require('ejs');

ejs.filters.fromNow = function(date){
  return moment(date).fromNow()
}
ejs.filters.formatDate = function(date){
  return moment(date).format('MMM Do YYYY');
}
ejs.open = '<?';
ejs.close = '?>';

Then in layout, view, it should be call

<td><?=: post.createdAt | formatDate ?></td>

Hope that help!

Update

For some reasons, you guys have to install module sails locally to make sense. So just paste to your console:

npm i sails

regards,

Anh Nguyen




回答3:


One way to accomplish this is through middleware. Something like:

module.exports.routes = {

  '*': function mixinForm(req, res, next) {
     // <%= form() %>
     res.locals.form = function () {
        return '<form action=""></form>';
     };
     next();
  },
}

I would also suggest making a feature request for a more integrated approach at: https://trello.com/b/cGzNVE0b/sails-js-feature-requests.



来源:https://stackoverflow.com/questions/21064365/where-to-access-and-store-ejs-helpers-sailsjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!