0

I have a working template engine (pug) to fill it's website with content depending from the situation. Acutally that template is rendered for the site '/show'.

Now I also need to change the url of this website depending from the content. That means I need the same template with new content for sites like: '/tree', '/house', '/urban' an do so. '/show' is the starting point, I need to change it's url with the new content.

I'm sure there is an easy answer, but I can't find the fitting question for that. So I can't find the right answer per searchengine. (Express.js res.render() and res.redirect() was my closest success, but it is not helpful for me.

I know, the following code is incorrect, at least because of the two resp.

server.get('/show', (req, resp) => {
    loadContent(function(err, content){
        if(content){
            resp.location('/tree');
            resp.render('myTemplate', content);
        } else{
            console.log(err);
        }
    })
});

How can I send my content to the template and replace the url to see both on the browser?

listener
  • 47
  • 7

3 Answers3

0

to send data to your pug template with express js use this syntax

const router = require('express').Router();
server.get('/show', (req, res, next) => {
 loadContent(function(err, content){
    if(content){
        res.render('myTemplate', { content: content });
    } else{
        console.log(err);
    }
   })

and you will get it

script.
var content = !{content};
Rebai Ahmed
  • 1,509
  • 1
  • 14
  • 21
0

Well, I've found my problem. My approach was incorrect.

With

server.get('/:kindOfSite', function(req, resp){...});

I'm able to load the same template for different sites.

Learning can get hard sometimes...

listener
  • 47
  • 7
0

Remember that your express route handlers are just functions. There's nothing that forces you to use an anonymous function. You can just use a regular function:

function handleRequest (req, resp) {
    loadContent(function(err, content){
        if(content){
            resp.location('/tree');
            resp.render('myTemplate', content);
        } else{
            console.log(err);
        }
    })
}

server.get('/show', handleRequest);
server.get('/tree', handleRequest);
server.get('/house', handleRequest);
server.get('/urban', handleRequest);

Indeed, you can do a bit of metaprogramming and call server.get() in a loop:

['/show','/tree','/house','/urban].forEach(route => {
     server.get(route,handleRequest)
});

In fact, Express accepts regular expressions as route paths:

server.get(/\/(show|tree|house|urban)/, (req, resp) => {
    loadContent(function(err, content){
        if(content){
            resp.location('/tree');
            resp.render('myTemplate', content);
        } else{
            console.log(err);
        }
    })
});
slebetman
  • 109,858
  • 19
  • 140
  • 171