【问题标题】:How to automate the creation of multiple ejs files with nodejs如何使用 nodejs 自动创建多个 ejs 文件
【发布时间】:2021-01-17 06:17:13
【问题描述】:

我目前正在创建一个博客网站,并且我有这个“撰写页面”,我可以在其中撰写文章。我目前正在使用 ejs,所以当文章发布时,数据会被保存。但是这些文章只能通过一个 ejs 文件访问。这是我的一些上下文代码:


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,
      })

    }
  })
});

但我希望我的 app.js 每次自动发布新文章时都会创建一个新的 ejs 文件。这可能吗?

【问题讨论】:

    标签: javascript node.js express ejs


    【解决方案1】:

    查看https://plopjs.com/documentation - 它使您能够以编程方式从模板生成不同的文件。

    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('/');
    })
    

    然后是 plop 命令中指定的文章参数的示例模板:

    const {{pascalCase title}}.article.ejs = ({ title, content, date }) => {
      return (
         <article>
           <h2>{title}</h2>
           <span>{date}</span>
           <section>{content}</section>
         </article>
      )  
    }
    

    【讨论】:

      猜你喜欢
      • 2013-07-01
      • 2018-12-17
      • 1970-01-01
      • 1970-01-01
      • 2018-05-10
      • 2021-01-18
      • 2020-09-06
      • 2012-06-06
      • 2015-10-11
      相关资源
      最近更新 更多