问题描述
我有一个基本的 Express 服务器:
I have a basic Express server:
// server.js:
var Express = require('express');
app = Express.createServer();
app.configure(function(){
app.set('views', Path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.set('view options');
});
app.get('/', function (request, response) {
response.render('welcome', {
locals: {some: 'Locals'}
});
});
使用基本的玉石布局:
// views/layout.jade:
!!! 5
html(lang='en')
head
title= pageTitle
body
h1= pageTitle
aside(id="sidebar")= sidebarContent
#content
#{body}
还有一个简单的页面:
# views/welcome.jade:
// How do I pass pageTitle and sidebarContent out to the layout from here?
p
Welcome to my fine site!
(在 Rails 中,这可能类似于 content_for
或一个简单的实例变量.)
(In Rails, this might be something like content_for
or a simple instance variable.)
推荐答案
使用上面关于 dynamicHelpers 的技巧和闭包的魔力,我找到了一个相当优雅的解决方案,它无需涉及请求对象即可工作.诀窍是将页面标题变量包装在一个闭包中,该闭包提供了一个 get() 和 set() 函数,并使该包装对象成为 page_title 动态助手的结果.
Using the tip above about dynamicHelpers, and the magic of closures, I found a fairly elegant solution that works without involving the request object. The trick is to wrap the page title variable in a closure that provides a get() and set() function around it, and make that wrapper object the result of the page_title dynamic helper.
创建一个property.js:
Create a property.js:
exports.create = function () {
var value = null;
return {
get: function () {
return value;
},
set: function (new_value) {
value = new_value;
}
};
}
因此调用 create() 返回一个带有 get() 和 set() 方法的对象,用于获取和设置闭包变量.
So calling create() returns an object with a get() and set() method on it, that get and set the closure variable.
然后,在您应用的设置代码中:
Then, in your app's setup code:
var property = require("./property.js");
app.dynamicHelpers ({
page_title: function () {
return property.create ();
}
});
由于动态助手的值是调用其函数的结果,因此在您的视图和模板中,page_title 变量将是具有 get() 和 set() 函数的包装对象.
Since the dynamic helper's value is the result of calling its function, in your view and template, the page_title variable will be the wrapper object with the get() and set() functions.
在您看来,您可以说:
- page_title.set ("my specific page title");
在您的布局中:
title= page_title.get()
为了进一步简化,将其添加到 property.js:
To simplify this a bit further, adding this to property.js:
exports.creator = function () {
return function () {
return exports.create();
};
}
让您将动态助手声明块简化为:
Lets you simplify the dynamic helpers declaration block to this:
var property = require("./property.js");
app.dynamicHelpers ({
page_title: property.creator()
});
这篇关于如何将内容从模板传递到 Express 中的布局?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!