Eduardo Humberto
Eduardo Humberto

Reputation: 485

How can I control the url path for dynamic rendering using express?

My problem is the following: I need to register 2 kinds of users (student and teacher), but the user controller is unique (there are just some optional values that I check on the controller according to the user form). What are my options to control what form should I render based on the request url ( or sending a variable from the route, for example).

Code below:

Routes

router.get('/newStudent', user_controller.user_create_get);
router.post('/newStudent', user_controller.user_create_post);

router.get('/newTeacher', user_controller.user_create_get);
router.post('/newTeacher', user_controller.user_create_post);

Controller

exports.user_create_get = function(req, res) {
    // here I would like to place an if to render newStudent or newTeacher 
    // according to the route path request

    res.render('newStudent');
    res.render('newTeacher');
}

Any advices are welcome. Also, should I build different controllers? Even if the register form is similar ?

Upvotes: 0

Views: 292

Answers (1)

Sparw
Sparw

Reputation: 2743

Maybe you can check req.path which will be /newTeacher or /newStudent like this :

exports.user_create_get = function(req, res) {
  if (req.path == '/newTeacher') {
    res.render('newTeacher');
  }
  else if (req.path == '/newStudent') {
     res.render('newStudent');
  }
  else {
     res.render('Error !');
  }
}

Hope it helps :)

Upvotes: 1

Related Questions