Template Inheritance for Handlebars
Asked Answered
L

4

11

I am trying for template inheritance from base.html to other templates using handlebars.But am not getting soul for this.

Please, Can anyone help me out with simple DEMO. with base.html , extend.html

For example , Base.html

<html><head></head>
<body>
{% block content %}{% endblock %}
</body>
</html>

Extend.html

{% extends "base.html" %}
{% block content %}<h1>Foobar!</h1>{% endblock %}

Which files I need to include in base.html ......?

Laurence answered 5/11, 2012 at 6:19 Comment(2)
templates need to be in script tags with ID's . Text for a title tag doesn't need a template, it's just text. You haven't explained any relationship between extend.html and base.html.Allan
express-hbs supporting itScriven
P
3

Handlebars does not provide template inheritance out-of-the-box.

However, there are libraries that provide the helpers necessary to do template inheritance. My favorite is Wax On because it is based on the template inheritance in Pug and Django and works as you expect.

There is also handlebars-layouts which works a little differently, but it can also run client-side, if needed.

Pacifica answered 16/6, 2017 at 1:40 Comment(0)
M
1

It's possible to extend partials to support 'blocks', see this gist.

Megaera answered 17/4, 2015 at 17:49 Comment(0)
F
0
// in my node server: using express and hbs 
hbs.registerPartials(__dirname + '/built/development/templates');
app.get('/', function (req, res) {
  res.render('_base', {
    "STATIC_URL": app.get('STATIC_URL')
  });
});

// This is in my base template 
<!--[if gt IE 8]><!--> <html class="no-js" lang="en" itemscope itemtype="http://schema.org/Article" xmlns:fb="http://ogp.me/ns/fb#"> <!--<![endif]-->
<head prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# blog: http://ogp.me/ns/blog#">
    {{> _config_logged_out }}
    {{> _scripts }}
</head>
Fisherman answered 29/9, 2013 at 2:40 Comment(0)
C
0

This can now be achived using the inline partials of native Handlebars:

<!-- template/base.html.hbs -->
<html><head></head>
<body>
{{#> content}}{{/content}}
</body>
</html>
<!-- template/extend.html.hbs -->
{{#> base.html}}
{{#*inline "content"}}<h1>Foobar!</h1>{{/inline}}
{{/base.html}}

Handlebars requires partials be registered before used. In Node.js you can do something like:

/* myscript.js */
const Handlebars = require('handlebars');
const fs = require('node:fs');
const {resolve, extname} = require('node:path');

// register each partial for template/<basename>.hbs as <basename>
const layoutDir = resolve(__dirname, 'template');
for (const file of fs.readdirSync(layoutDir)) {
  const ext = extname(file);
  if (ext.toLowerCase() !== '.hbs') {
    continue;
  }
  Handlebars.registerPartial(
    file.slice(0, -ext.length),
    fs.readFileSync(resolve(layoutDir, file), 'utf-8')
  );
}
Chant answered 12/8, 2024 at 23:35 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.