Skip to content
Advertisement

How to automate the creation of multiple ejs files with nodejs

I am currently making a blog site and I have this “compose page” where I can write articles. I’m currently using ejs so when the article is posted the data gets saved. But these articles are accessed on one ejs file only. Here is my code for some context:

let posts = [];
app.get('/', (req,res)=>{
  res.render('home.ejs',{
    posts: posts,
    defaultContent: homeStartingContent,
  })
})
app.get('/about', (req,res)=>{
  res.render('about.ejs', {
    aboutContent: aboutContent,
  })
})
app.get('/contact', (req,res)=>{
  res.render('contact.ejs', {
    contactContent: contactContent,
  })
})
app.get('/compose', (req,res)=>{
  res.render('compose.ejs')
})
app.post('/compose', (req,res)=>{
  let article = {
    title: req.body.titleContent,
    date: req.body.dateContent,
    content: req.body.content,
  }
  posts.push(article);
  res.redirect('/');
})
app.get('/posts/:topic',(req,res)=>{
  let reqTitle = _.kebabCase(req.params.topic);
    
  posts.forEach((post)=>{
    
    if (_.kebabCase(post.title) === reqTitle){
      res.render('post.ejs', {
        title: post.title,
        date: post.date,
        content: post.content,
      })

    }
  })
});

But I want my app.js to make a new ejs file everytime I post a new article automatically. Is this possible?

Advertisement

Answer

Check out https://plopjs.com/documentation – it enables you to programmatically generate different files from templates.

app.post('/compose', (req,res)=>{
  let article = {
    title: req.body.titleContent,
    date: req.body.dateContent,
    content: req.body.content,
  }
  posts.push(article);
  plop(article, title, content, date); <--- custom plop command
  res.redirect('/');
})

and then an example template for the article param specified in your plop command:

const {{pascalCase title}}.article.ejs = ({ title, content, date }) => {
  return (
     <article>
       <h2>{title}</h2>
       <span>{date}</span>
       <section>{content}</section>
     </article>
  )  
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement