资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

Express.js中的locals用法

引子

蒙山网站制作公司哪家好,找创新互联!从网页设计、网站建设、微信开发、APP开发、成都响应式网站建设公司等网站项目制作,到程序开发,运营维护。创新互联2013年开创至今到现在10年的时间,我们拥有了丰富的建站经验和运维经验,来保证我们的工作的顺利进行。专注于网站建设就选创新互联。

在Express.js 4.x框架中存在两个locals定义。一个是Express本身带有的locals属性(Object类型),另一个是Response的locals属性(Object类型)。

在本文中,我们来讨论一下Express本身带有的locals属性用法。

Express.js 2.x时代

先看历史:在Express.js 2.x时代,还没有出现locals,而是使用app.helpers 和app.dynamicHelpers 。在express2.X中,你可以使用它们分别作为静态/动态视图助手工具。

有一个简单的例子,如下:

app.helpers({
inspect: function(obj) {
return util.inspect(obj, true);
}
});


Express.js 3.X/4.X时代

如今,Express本身带有的locals属性把上述两个Helper替换掉了。官方说法是:


The app.locals object is a JavaScript object, and its properties are local variables within the application.


也就是说,你可以在Express程序的生命周期内为其locals这个对象属性定义任意你喜欢的属性(当然包括函数),然后在你需要的地方使用。但是,有重要提示与说明,如下:


Once set, the value of app.locals properties persist throughout the life of the application, in contrast with res.locals properties that are valid only for the lifetime of the request.

You can access local variables in templates rendered within the application. This is useful for providing (1)helper functions to templates, as well as (2)app-level data. Note, however, that you CANNOT access local variables in middleware.


上面的E文不用我翻译了,翻译得拙劣反而会歪曲的原文主旨。


因此,作者在新版本中作上述更新(当然是替换)是极有道理的。因此,在新版本中(时下最流行的自然是4.X),locals的作用进一步扩展,而不仅限于作为模板视图的工具函数使用。

值得注意的是,3.X与4.X中也有一些不同(摘录http://blog.csdn.net/ling369523246/article/details/49487509的例子如下):

............

但是在express 3.x后 这两个方法被废止。

3.x 使用的是 


app.locals({
   key2: value1,
   key2: value2
})
就有如下:
app.locals({
 inspect: function(obj) {
 return util.inspect(obj, true);
}
});


但是express4.x后变化就很大了
app.locals.key1 = value1;app.locals.key2 = value2; 
如下:app.locals.inspect=function(obj){
    return util.inspect(obj, true);
}

在.jade模板中使用locals简介

至于在.jade等模板中如何使用locals中定义的属性,在stackoverflow中有相应的解决,而且来自express.js作者TJ Holowaychuck,示例及说明如下。

下面这一段不是来自EXPRESS.JS作者(尽管使用的是3.0,现在不再有):

Here is an example using a fresh installation of express v3.0.0rc4

app.js:

app.use(function(req, res, next){
  res.locals.variable="Hello locals from Response!";
  next();
  }
)
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');

app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());

app.use(express.static(path.join(__dirname, 'public')));
});

index.jade:

extends layout

block content
  h2= title
  p Welcome to #{title}
  p=variable

注意,上面例子中使用了Response对象中定义的locals,运行结果如下图所示:

Express.js中的locals用法

来自express.js作者TJ Holowaychuck的上述使用忠告则强调了使用顺序:

the one key thing you have to remember (currently), is that all of the 
routes (app.get, app.put, etc) 
are part of a routing middleware called app.router (this is an 
instance of a Router). So app.use() 
works with individual middleware, so if you call it between two 
app.get() calls for example it's 
not actually added between them. 

so you might want to do something like: (这里使用示例说明使用顺序的问题)

app.use(loadViewData); 
app.use(app.router); 

app.get('/..... 

that way it's before the routes. 

I should note that I've played with each app.{get,put,...}() call 
being its 
own middleware, which is nice in a lot of ways but I need to improve 
the 
performance of that solution before considering it

使用了Express对象中定义的locals简介

使用Express对象中定义的locals详细分析起来要复杂一些。正如上面解释的,至少应当考虑两种情形:在模板引擎中如何使用Express对象中定义的locals;第二,作为app-level data如何使用Express对象中定义的locals。


在此,仅看一下第一种情形的举例。


在app.js中,有如下定义:

app.use(function(req, res, next){
  app.locals.appvariable={
    "key1":"Hello locals",
    "key2":121,
    "startX":function(){console.log("xxxxxxxxxx.");}
  };
  app.locals.tt=function(){console.log("MMMMMMMMMMM");};
  //app.locals.startX=function(para1,para2){
  //  console.log("Now start starting...");
  //};
  res.locals.variable = "Hello locals from Response!";
  next();//MUST HAVE
});

那么,在模板文件index.jade中可以使用如下表达方式:

extends layout

block content

  h2= title

  p Welcome to #{title}

  p=variable

  br

  h3=appvariable.key1


关于更一般作为express应用程序生命周期内data使用的locals属性的用法,在此恕不介绍,有兴趣的朋友可以进一步探讨这方面的应用。

关于Express中的locals属性用法讨论至此,欢迎一起作进一步探讨......





标题名称:Express.js中的locals用法
本文网址:http://cdkjz.cn/article/gsjejj.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220