Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

289
Views
dynamic rendering in express using loop won't work

I have bunch of static file, they are named article1, article2 and so on. So I know it worked when I do

app.get('/this-is-my-article-routes', (req, res) => {
        res.render('article1');
});

but it's too tedious and has lots of repeated code. I tried this but it doesn't work?

const articleArr = [
    'this-is-my-article-routes'
];

for (i = 0; i<9; i++) {
    app.get(`/${articleArr[i]}`, (req, res) => {
        res.render(`article${i}`);
    });
}

Is this even possible? or there's something wrong with my codes?

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

how about simple solution using query params 
app.get('articleArr/:id', (req, res) => {
        res.render('article/'+req.params.id);
    });
about 4 years ago · Santiago Trujillo Report

0

Does your array articleArr contains 10 elements?

I think, the better way to do this would be:

var articleList = [ 'first', 'second', 'third']
app.get('/:article', (req, res) {
    var articleName = req.params.article
    var index       =  articleList.indexOf(articleName)
    if (index == -1) {
        // No Aricle Found
    }
    res.render(`articles$(index)`)
})

This code will also work fine but it is not the recommended one.

var articleList = ['first', 'second']
articleList.forEach(function(value){
    app.get('/'+value, (req, res) => {
        res.status(200).json({
            value: value
        })
    })
})
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!