How do I use layouts, partials with handlebars template like the following?
I have looked at the partial docs but still could not figure out what I wanted to achieve.
default.html
The default layout is reused for the different views of the site. {{{content}}}
is used as a placeholder for where the main content will be rendered.
<!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>
index.html
{{#> default}}
{{ include header }}
<p>This is some other content</p>
{{ include footer }}
header.html
<h1>This is a header</h1>
footer.html
<p>This is a footer</p>
Output
<!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>
First to make the partial work first remove the sharp(#) in front of your partial call in index.html.
{{> default}}
Second : you won't be able to build a whole page (with headers) using handlebars : the javascript is loaded once the page has been loaded so headers are already sent and can't be modified. Handlebars.js is only useful if you want to manipulate the DOM to put your template result in a container.
You have an example of what can be done here: 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);
});
I hope the example will help ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With