在Node.js中使用插值EJS包括 [英] Using interpolation within Node.js EJS includes

查看:239
本文介绍了在Node.js中使用插值EJS包括的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

My Express应用程序正在使用EJS,我的views目录如下所示:

My Express app is using EJS, and my views directory looks like this:

./views
  ./contents
    home.ejs
  ./includes
    header.ejs
    footer.ejs
  layout.ejs

我试图在我的layout.ejs视图中加载home.ej,有条件地基于一个名为内容的本地变量在我的路线/ index.js。该文件如下所示:

I'm trying to load home.ejs in my layout.ejs view conditionally based on a local variable named contents in my routes/index.js. That file looks like this:

/*
 * GET home page.
 */

exports.index = function(req, res){
  res.render('index', { title: 'Home', contents: 'home.ejs' });
};

理想情况下,我可以简单地写(在layout.ejs中):

Ideally I could simply write (in layout.ejs):

<% include '/contents' + contents %>

其中尾随的内容是包含要加载的正文文本的相对路径的局部变量

where the trailing "contents" is the local variable which contains the relative path to the body text to load.

但是,看起来,EJS总是解释文本后面的 include 指令,而且没有机会任何插补魔法都会发生。

But alas, it appears EJS always interprets the text following an include directive literally, and there is no chance for any interpolation magic to happen.

我也试图无效:

<% function yieldContent(contents){ %>
  <% var contentPath = 'contents/' + contents; %>
  <% include contentPath %>
<% }; %>
<% loadContent(); %>

有没有人有创意解决方案有条件地包含基于路由中传递的变量的视图?

Does anyone have a creative solution for conditionally including a view based on a variable passed in routes?

推荐答案

我认为没有办法做这种动态包括在EJS中。这可能会破坏业务逻辑和观点的分离。
解决方案可以在控制器中呈现子模板,并将其内容传递给布局。

I think there is no way to do this kind of dynamic includes in EJS. It might break the separation of business logic and view. The solution can be to rendering the subtemplate in the controller, and passing its content to the layout.

对于控制器中的渲染子模板,使用如下所示:

For rendering subtemplate in the controller use something like this:

var ejs = require('ejs'),
, fs = require('fs')
, home = ejs.render(fs.readFileSync("contents/home.ejs", "utf-8"))

这篇关于在Node.js中使用插值EJS包括的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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