Express學(xué)習(xí)筆記

安裝

$ npm install express

Handlebars模板引擎

安裝

$npm install --save express-handlebars
在express中引入
var handlebars=require('express-handlebars').create({defaultLayout:"main"});
app.engine('handlebars',handlebars.engine);
app.set('biew engine','handlebars');

默認是使用main模板

app.get('/foo',function(reqres){
      res.render('foo');
})
//會使用views/layouts/main.handlebars作為布局

如果不想使用布局:

app.get('/foo',function(reqres){
      res.render('foo',{layout:null});
})

如果想指定模板

app.get('/foo',function(reqres){
      res.render('foo',{layout:'microsite'});
})
//會使用views/layouts/microsite.handlebars作為布局

注釋

不會被傳到瀏覽器:

{{! super-seret comment}}

會被傳到瀏覽器

<!--not-so-secret-comment-->

變量

{{name}}
{{{body}}}//關(guān)閉HTML轉(zhuǎn)義

局部文件

{{> weather}}
//會在views/partials中尋找weather.handlebars

引用子目錄中的

{{> tools/weather}}
//會在views/partials/tools中尋找weather.handlebars

段落

場景:視圖本身需要添加到布局的不同部分

var handlebars=require('express-handlebars').create({
      defaultLayout:"main",
      helpers:{
              section:function(name,options){
                   if(!this._sections) this._sections={};
                   this._sections[name]=options.fn(this);
                   return null;
              }
        }
});

視圖中使用section輔助方法,創(chuàng)建視圖(views/jquerytest.handlebars),在<head>中添加一些東西,并添加一段使用jquery的腳本:

{{#section 'head'}}
    <!-- let google to ignore this page -->
    <meta name="robots" content="noindex">
{{/section}}
<h1>TEst Page</h1>
<p>test something</p>

{{#section 'jquery'}}
    <script>
        $('document').ready(function(){
            $('h1').html('jquery works');
        })
    </script>
{{/section}}

現(xiàn)在在布局里可以相當之{{{body}}}一樣當值一個段落

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Document</title>
    {{{_section.head}}}
</head>
<body>
    {{{body}}}
    <script src="http://code.jquery.com/jquery-2.0.2.min.js"></script>
    {{{_section.jquery}}}
</body>
</html>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容