ThinkNewDev
ThinkNewDev

Reputation: 668

How can I make my express route more dynamic

I want to make my express route have the ability be able to pass anything past the first set of parameters to it

app.get('/views/app/:name/*', appRoutes.partials);

and in my route file I have

exports.partials = function(req, res) {
    var name = req.params.name;
    var partial = req.params.partial;
    var content = "";
    res.render('views/app/'+name+'/'+partial,content);
};

I know partial would not be the variable to use there but how can I make whatever passes through the star append to the end?

I hope this makes sense.

Upvotes: 0

Views: 665

Answers (1)

panta82
panta82

Reputation: 2721

The star (*) placeholder will capture all the remaining text and place it under key '0' on params object (if you had more *'s, they would go to '1', '2'...).

So, how about this:

exports.partials = function(req, res) {
    var name = req.params.name;
    var partial = req.params['0'];
    var content = "";
    res.render('views/app/'+name+'/'+partial,content);
};

If you expect the wildcard part to be an arbitrary route, you will have to parse it yourself. For example:

// url: /views/app/profile/main/dashboard
exports.partials = function(req, res) {
    var path = req.params['0'].split('/');
    console.log(path[0], path[1]); //>> main dashboard
};

Upvotes: 1

Related Questions