Express.js中的locals用法-創(chuàng)新互聯(lián)

引子

創(chuàng)新互聯(lián)公司專注于焉耆網(wǎng)站建設(shè)服務(wù)及定制,我們擁有豐富的企業(yè)做網(wǎng)站經(jīng)驗(yàn)。 熱誠為您提供焉耆營銷型網(wǎng)站建設(shè),焉耆網(wǎng)站制作、焉耆網(wǎng)頁設(shè)計(jì)、焉耆網(wǎng)站官網(wǎng)定制、小程序設(shè)計(jì)服務(wù),打造焉耆網(wǎng)絡(luò)公司原創(chuàng)品牌,更為您提供焉耆網(wǎng)站排名全網(wǎng)營銷落地服務(wù)。

在Express.js 4.x框架中存在兩個(gè)locals定義。一個(gè)是Express本身帶有的locals屬性(Object類型),另一個(gè)是Response的locals屬性(Object類型)。

在本文中,我們來討論一下Express本身帶有的locals屬性用法。

Express.js 2.x時(shí)代

先看歷史:在Express.js 2.x時(shí)代,還沒有出現(xiàn)locals,而是使用app.helpers 和app.dynamicHelpers 。在express2.X中,你可以使用它們分別作為靜態(tài)/動(dòng)態(tài)視圖助手工具。

有一個(gè)簡(jiǎn)單的例子,如下:

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

Express.js 3.X/4.X時(shí)代

如今,Express本身帶有的locals屬性把上述兩個(gè)Helper替換掉了。官方說法是:

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

也就是說,你可以在Express程序的生命周期內(nèi)為其locals這個(gè)對(duì)象屬性定義任意你喜歡的屬性(當(dāng)然包括函數(shù)),然后在你需要的地方使用。但是,有重要提示與說明,如下:

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文不用我翻譯了,翻譯得拙劣反而會(huì)歪曲的原文主旨。

因此,作者在新版本中作上述更新(當(dāng)然是替換)是極有道理的。因此,在新版本中(時(shí)下最流行的自然是4.X),locals的作用進(jìn)一步擴(kuò)展,而不僅限于作為模板視圖的工具函數(shù)使用。

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

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

但是在express 3.x后 這兩個(gè)方法被廢止。

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簡(jiǎn)介

至于在.jade等模板中如何使用locals中定義的屬性,在stackoverflow中有相應(yīng)的解決,而且來自express.js作者TJ Holowaychuck,示例及說明如下。

下面這一段不是來自EXPRESS.JS作者(盡管使用的是3.0,現(xiàn)在不再有):

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對(duì)象中定義的locals,運(yùn)行結(jié)果如下圖所示:

Express.js中的locals用法

來自express.js作者TJ Holowaychuck的上述使用忠告則強(qiáng)調(diào)了使用順序:

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對(duì)象中定義的locals簡(jiǎn)介

使用Express對(duì)象中定義的locals詳細(xì)分析起來要復(fù)雜一些。正如上面解釋的,至少應(yīng)當(dāng)考慮兩種情形:在模板引擎中如何使用Express對(duì)象中定義的locals;第二,作為app-level data如何使用Express對(duì)象中定義的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中可以使用如下表達(dá)方式:

extends layout

block content

 h2= title

 p Welcome to #{title}

 p=variable

 br

 h3=appvariable.key1

關(guān)于更一般作為express應(yīng)用程序生命周期內(nèi)data使用的locals屬性的用法,在此恕不介紹,有興趣的朋友可以進(jìn)一步探討這方面的應(yīng)用。

關(guān)于Express中的locals屬性用法討論至此,歡迎一起作進(jìn)一步探討......

另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無理由+7*72小時(shí)售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡(jiǎn)單易用、服務(wù)可用性高、性價(jià)比高”等特點(diǎn)與優(yōu)勢(shì),專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場(chǎng)景需求。

網(wǎng)站名稱:Express.js中的locals用法-創(chuàng)新互聯(lián)
URL鏈接:http://muchs.cn/article32/dchesc.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供自適應(yīng)網(wǎng)站、動(dòng)態(tài)網(wǎng)站、定制開發(fā)、營銷型網(wǎng)站建設(shè)服務(wù)器托管、企業(yè)網(wǎng)站制作

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

h5響應(yīng)式網(wǎng)站建設(shè)