使用布局,带有把手模板的部分

Ish*_*han 6 html javascript template-engine template-inheritance handlebars.js

我如何使用布局、partials 和如下所示的把手模板?

我查看了部分文档,但仍然无法弄清楚我想要实现的目标。

默认.html

默认布局被重复用于站点的不同视图。{{{content}}}用作主要内容将被呈现的位置的占位符。

<!DOCTYPE html>
<html>
<head>  
  <title>{{title}}</title>
</head>
<body>
 <p>This is the top of the body content in the default.html file</p>
 {{{content}}}
 <p>This is the bottom of the body content in the default.html file</p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

索引.html

{{#> default}}

{{ include header }}
<p>This is some other content</p>
{{ include footer }}
Run Code Online (Sandbox Code Playgroud)

标题.html

<h1>This is a header</h1>
Run Code Online (Sandbox Code Playgroud)

页脚.html

<p>This is a footer</p>
Run Code Online (Sandbox Code Playgroud)

输出

<!DOCTYPE html>
<html>
<head>  
  <title>Using Layout, Partials with Handlebars Template</title>
</head>
<body>
 <p>This is the top of the body content in the default.html file</p>
 <h1>This is a header</h1>
 <p>This is some other content</p>
 <p>This is a footer</p>
 <p>This is the bottom of the body content in the default.html file</p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

Chr*_*phe 3

  • 首先要使部分工作首先删除index.html 中部分调用前面的尖号(#)。

    {{> 默认}}

  • 其次:您将无法使用handlebars构建整个页面(带有标题):页面加载后就会加载javascript,因此标题已经发送并且无法修改。仅当您想要操作 DOM 以将模板结果放入容器中时,Handlebars.js 才有用。

您有一个可以在此处完成的示例: https ://jsfiddle.net/ChristopheThiry/zepk5ebh/4/

<script id="default" type="text/x-handlebars-template">
 <p>This is the top of the body content in the default.html file</p>
 {{{content}}}
 <p>This is the bottom of the body content in the default.html file</p>
</script>

<script id="index" type="text/x-handlebars-template">
{{include header }}
{{> default}}
{{include footer }}
</script>

<div id="resultPlaceholder">
</div>

$(document).ready(function () {
  var defaultSource   = $("#default").html();
  var indexSource = $("#index").html();
  Handlebars.registerPartial('default',defaultSource);
  Handlebars.registerHelper('include', function(source) {
        return new Handlebars.SafeString(source);
});
  var template = Handlebars.compile(indexSource);
  var context = { "content" : "<b>This is some other content</b>","header" : "<h1>This is a header</h1>", "footer" : "<div class='footer'>This is a footer</div>"} ;
  var html    = template(context);
  $("#resultPlaceholder").html(html);
});
Run Code Online (Sandbox Code Playgroud)

我希望这个例子能有所帮助......