Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

291
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda