Reloading partials Handlebars

Ambroise Collon picture Ambroise Collon · Jul 1, 2013 · Viewed 8.1k times · Source

I'm quite new to programming and especially to handlebars. I have a div loaded with combination of jquery and handlebars in my html file. I have tabs on top of it. I want to reload all the content to a new one when there is a click on a tab. The content is similar (same structure) but labels, images and so on have to change. I tryed to use the partial in handlebars.js. Here is a sample code.

<script type="text/x-handlebars-template" id="all-handlebar">
    {{#each tabs}}
        <div id=tab{{@index}}>{{this.text}}</div>
    {{/each}}
    <div id="tab-content">{{> tabContentPartial}}
</script>
<script type="text/x-handlebars-template" id="tab-content-partial"> 
    <div id="mycontent">
        <div id="text">{{mycontent.text}}</div>
        <div id="text">{{mycontent.image}}</div>
    </div>      
</script>
<script type="text/javascript">
    source=$("#all-handlebar").html();
    var template = Handlebars.compile(source);
    Handlebars.registerPartial("tabContentPartial", $("#tab-content-partial").html())
    var context = {
        mycontent : {
            text="something that has to change everytime I click on a different tab",
            image="idem"
    };
    var html = template(context);
    $("body").html(html);
</script>

It loads well the first time but when I click on the tab, I ask him to re-registerPartial the tab-content-partial script and it doesn't exist anymore because it has changed to HTML block right in my code. How can reuse and reload my partial script with new contents ?

Thank you very much !

Answer

t.niese picture t.niese · Jul 2, 2013

The tab switching part of your code is missing and also how you retrieve your data, so I can only tell you what you need to do at the place where you listen to your tab switching.

To achieve this you just need to also compile your #tab-content-partial for this you don't need to change much:

var source=$("#all-handlebar").html();
var contentSrc=$("#tab-content-partial").html();
var template = Handlebars.compile(source);
var contentTemplate = Handlebars.compile(contentSrc);

//because you already have a compiled version of your content template now you can pass this as partial
Handlebars.registerPartial("tabContentPartial", contentTemplate);
var context = {
    mycontent : {
        text : "something that has to change everytime I click on a different tab",
        image : "idem"
    }
 };

var html = template(context);
$("body").html(html);

Then at the time where you need to change the content you will just pass the data of the content to the content template and then replace the content of #tab-content with the new result. This way you could also create different content templates.

//replace the content with the result of the template
$("#tab-content").html( contentTemplate(newContent) );

I hope this is what you where looking for, if not feel free to ask.