EJS(node.js)中的动态模板 [英] Dynamic templates in EJS (node.js)

查看:152
本文介绍了EJS(node.js)中的动态模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有人知道一个很好的解决方案,包括模板,其名字只能在运行时才知道? 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 ??? %GT;
< / article>
< / section>

有没有可能这样做,或者唯一的选择是加载文章内容并放入articleContent ,所以可以通过<% - articleContent%>



此解决方案的问题是文章的内容应该是纯HTML(`<% - - %>'不插值)。所以如果在文章中我需要使用任何EJS功能,我需要自己编译/渲染。



也许有人已经知道如何使用EJS的一些动态包含助手来完成这个任务,所以不需要额外的代码?

解决方案

看来EJ现在支持这一点吗?它已在 v2.0.1:2015-01 -02 。新的语法看起来像这样

 <% -  include(articleContent)%> 

要使其正常工作我必须通过设置禁用Express中的缓存:

  app.set('view cache',false); 


Does anybody know a nice solution for including templates, whose names would be known only at run time? EJS's includes allows only to specify exact file/template name.

Use case: I have a article layout and there is article HTML/EJS content in some local file.

To do so I need something like https://github.com/visionmedia/ejs#includes but file name should be taken from locals variable:

Assume I have such handler (simplified):

app.get('/article/:article', function (req, res) {
        var articleContent = req.params.article;
        res.locals.articleContent = 'data/'+articleContent;
        return res.render('article.ejs')
    })

And in article.ejs (assume having ejs-locals):

<% layout('layout') -%>
<section>
  <article class="single-country">
      <% include ???articleContent???  %>
  </article>
</section>

Is there any possibility to do so or is the only option is to load article content and put into articleContent, so available by <%- articleContent %>?

The problem with this solution is that the content of article should be plain html (`<%- -%>' do not interpolate value). So if inside article I need to use any EJS feature, I need to compile/render by myself.

Maybe someone else already knows how this can be done with some dynamic include helper for EJS so no need of additional code?

解决方案

Looks like this is now supported in EJS. It was introduced in v2.0.1: 2015-01-02. The new syntax looks like this

 <%- include(articleContent) %>

To get this to work I had to disable caching in Express by setting:

app.set('view cache', false);

这篇关于EJS(node.js)中的动态模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆