visionmedia/express — Issue #978: New little add-on section and define for view with HBS enabled
Author: dezofie
Created: 2012-01-26 02:03:43+00:00
State: open

Hi,

I stumbled upon your awsome project and I found out that this is great project to have play around. Everything great except I found little missing part inside view. It has missing on defining section inside template. Here is the simple overview on the problem:

I am using view engine, HBS. I defined the layout and the view for each routes.
layout.hbs:

title

{{#section "head" context}}
{{{body}}}
{{/section}}

{{{body}}}

And this is the view for each routes:
index.hbs:
{{#define "head" context}}

{{/define}}

this is child HTML

note that, I have two custom helpers inside HBS template, what they are:
- section: a placeholder inside layout HBS to display what defined inside child HBS
- define: ability to register what is the HTML to be rendered inside section

app.js to define the helpers functions
// views
// this is small hack to hold all the HTML but well... :)
hbs.sections = [];

// register helper for parent to hold the section
hbs.registerHelper("section", function(name, context, fn)
{
// make sure context is defined
context = (!_.isArray(context)) ? [] : context;
// register the body into the template
context["body"] = hbs.sections[name];
// render it
return fn(context);
});
// register helper for child to define the section
hbs.registerHelper("define", function(name, context, fn)
{
// register the pre-compiled HTML inside child
hbs.sections[name] = fn(context);
// make sure return nothing
return "";
});

Is that possible to roll this out inside your view engine? Across all other view type, jade, ejs, etc... I found it is possible inside HBS but I am not sure with other. I hope this will help other who is having the same difficulty that I have. Enjoy!