我的Express应用程序正在使用EJS,我的views目录如下所示:
./views
./contents
home.ejs
./includes
header.ejs
footer.ejs
layout.ejs
Run Code Online (Sandbox Code Playgroud)
我正在尝试根据contents
我的routes/index.js中命名的局部变量有条件地在layout.ejs视图中加载home.ejs .那个文件看起来像这样:
/*
* GET home page.
*/
exports.index = function(req, res){
res.render('index', { title: 'Home', contents: 'home.ejs' });
};
Run Code Online (Sandbox Code Playgroud)
理想情况下,我可以简单地写(在layout.ejs中):
<% include '/contents' + contents %>
Run Code Online (Sandbox Code Playgroud)
其中尾部"contents"是局部变量,其中包含要加载的正文文本的相对路径.
但是,似乎EJS总是按照include
字面上的指令来解释文本,并且没有机会发生任何插值魔法.
我也试过无济于事:
<% function yieldContent(contents){ %>
<% var contentPath = 'contents/' + contents; %>
<% include contentPath %>
<% }; %>
<% loadContent(); %>
Run Code Online (Sandbox Code Playgroud)
有没有人有条件地包含基于路线中传递的变量的视图的创造性解决方案?
我觉得这对于我对Ruby和面向对象编程的总体理解是至关重要的,所以我在这里提出这个相当简单的问题,冒着看起来很愚蠢的风险.我一直在玩弄irb.我创造了我的第一堂课:
$ irb
ruby-1.9.2-p290 :001 > class Person
ruby-1.9.2-p290 :002?> attr_accessor :firstname, :lastname, :gender
ruby-1.9.2-p290 :003?> end
=> nil
ruby-1.9.2-p290 :004 > person_instance = Person.new
=> #<Person:0x007f9b7a9a0f70>
ruby-1.9.2-p290 :005 > person_instance.firstname = "Bob"
=> "Bob"
ruby-1.9.2-p290 :006 > person_instance.lastname = "Dylan"
=> "Dylan"
ruby-1.9.2-p290 :007 > person_instance.gender = "male"
=> "male"
Run Code Online (Sandbox Code Playgroud)
所以Person.new
是我的目标,对不对?或者我的对象是我class Person
为该类定义的属性和属性的组合?