如何用nodejs自动创建多个ejs文件
How to automate the creation of multiple ejs files with nodejs
我目前正在制作一个博客网站,我有一个可以写文章的“撰写页面”。我目前正在使用 ejs,所以当文章被 posted 时,数据被保存。但是这些文章只能在一个 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 每次 post 一篇新文章时自动创建一个新的 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 命令中指定的文章参数的示例模板:
const {{pascalCase title}}.article.ejs = ({ title, content, date }) => {
return (
<article>
<h2>{title}</h2>
<span>{date}</span>
<section>{content}</section>
</article>
)
}
我目前正在制作一个博客网站,我有一个可以写文章的“撰写页面”。我目前正在使用 ejs,所以当文章被 posted 时,数据被保存。但是这些文章只能在一个 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 每次 post 一篇新文章时自动创建一个新的 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 命令中指定的文章参数的示例模板:
const {{pascalCase title}}.article.ejs = ({ title, content, date }) => {
return (
<article>
<h2>{title}</h2>
<span>{date}</span>
<section>{content}</section>
</article>
)
}