有没有人知道包含模板的好解决方案,模板的名称只能在运行时知道? EJS 的包含仅允许指定确切的文件/模板名称。
用例:我有一个文章布局,并且在某个本地文件中有文章 HTML/EJS 内容。
为此我需要类似 https://github.com/visionmedia/ejs#includes 的东西但文件名应取自本地变量:
假设我有这样的处理程序(简化):
app.get('/article/:article', function (req, res) {
var articleContent = req.params.article;
res.locals.articleContent = 'data/'+articleContent;
return res.render('article.ejs')
})
在 article.ejs 中(假设有 ejs-locals):
<% layout('layout') -%>
<section>
<article class="single-country">
<% include ???articleContent??? %>
</article>
</section>
是否有可能这样做,或者唯一的选择是加载文章内容并放入文章内容中,因此可用 <%- articleContent %>
?
此解决方案的问题是文章的内容应该是纯 html(“<%- -%>”不插入值)。因此,如果在文章中我需要使用任何 EJS 功能,我需要自己编译/渲染。
也许其他人已经知道如何使用 EJS 的一些动态包含帮助程序来完成此操作,因此不需要额外的代码?
最佳答案
Looks like this is now supported in EJ S.它是在v2.0.1: 2015-01-02中介绍的.新语法看起来像这样
<%- include(articleContent) %>
为了让它工作我必须通过设置禁用 Express 中的缓存:
app.set('view cache', false);
关于javascript - EJS (node.js) 中的动态模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20775710/