如何使用nodejs自动创建多个ejs文件



我目前正在制作一个博客网站,我有这个"撰写页面"在那里我可以写文章。我目前正在使用ejs,所以当文章发布时,数据得到保存。但是这些文章只能在一个ejb文件上访问。下面是一些上下文的代码:


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文件,每次我自动发布一篇新文章。这可能吗?

查看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命令中指定的article参数的示例模板:

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

最新更新