温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Express.js中的locals用法

发布时间:2020-04-10 17:01:54 来源:网络 阅读:3415 作者:googlingman 栏目:web开发

引子

在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({
<span ></span>inspect: function(obj) {
<span ></span>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属性用法讨论至此,欢迎一起作进一步探讨......






向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI