Express学习笔记

安装

$ 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}}}//关闭HTML转义

局部文件

{{> 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辅助方法,创建视图(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}}

现在在布局里可以相当之{{{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>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容