☚ GZOOL Quality Without A Name

Web Development with Node and Express Chapter 7 - Templating with Handlebars

使用模板引擎可以解决上面这些问题。

app.set('view cache', true);

SEVER:

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

VIEW:

{{#section 'head'}}
<!-- we want Google to ignore this page -->
<meta name="robots" content="noindex">
{{/section}}
<h1>Test Page</h1>
<p>We're testing some jQuery stuff.</p>
{{#section 'jquery'}}
<script>
$('document').ready(function(){
  $('h1').html('jQuery Works');
});
</script>
{{/section}}

LAYOUT:

<!DOCTYPE html>
<html>
  <head>
    <title>Meadowlark Travel</title>
    {{{_sections.head}}}
  </head>
  <body>
    {{{body}}}
    <script src="http://code.jquery.com/jquery-2.0.2.min.js"></script>
    {{{_sections.jquery}}}
  </body>
</html>
comments powered by Disqus