Marcelo Boeira
Marcelo Boeira

Reputation: 880

SailsJS - Helper Module to create links

I want to create helpers ...

like

function linkTo (value, href, options) { ..... }

But I want this to be global, so I can use to put the links at my views files,

<%= linkTo('link','/controller/action') %>

Instead of

<a href="/controller/action"> Link </a>

Should I use a service?

Upvotes: 0

Views: 728

Answers (1)

Jason Kulatunga
Jason Kulatunga

Reputation: 5894

Sails is built on top of Express and Express allows you to specify view locals. Just register your functions as middleware in config/http.js.

/config/http.js

module.exports.http = {

  customMiddleware: function (app) {
    app.use(function (req, res, next) {
      res.locals.linkTo = function(href, label){
        sails.log("linkTo works!", href, label);
      }
      next();
    });
  }
...
}

And use them in your view

<%= linkTo('link','/controller/action') %>

If you're looking for linkTo specifically, theres a library already written for ejs+express that has what you're looking for + many more

https://github.com/mhayashi/express-helpers

Upvotes: 1

Related Questions