How do I load different partials dynamically using handlebars templates?

后端 未结 3 659
慢半拍i
慢半拍i 2021-01-31 05:46

I\'m loading a template with the following data:

\"slides\": [
    {
        \"template\": \"video\",
        \"data\": {
            \"video\": \"\"
        }
          


        
3条回答
  •  说谎
    说谎 (楼主)
    2021-01-31 05:51

    As far as I can tell, hbs expects the partials to be known at compile time, which is way before you pass in your data. Let's work around that.

    First, pull in your dynamic partials before rendering, something like:

    // I required the main template here for simplicity, but it can be anywhere
    var templates = ['hbs!resources/templates/maintemplate'], l = data.slides.length;
    for (var i=0; i

    And define a helper that will act as a dynamic partial

    define(['Handlebars'], function (Handlebars) {
    
        function dynamictemplate(template, context, opts) {
            template = template.replace(/\//g, '_');
            var f = Handlebars.partials[template];
            if (!f) {
                return "Partial not loaded";
            }
    
            return new Handlebars.SafeString(f(context));
        }
    
        Handlebars.registerHelper('dynamictemplate', dynamictemplate);
        return dynamictemplate;
    });
    

    Finally, modify your main template to look like

    {{#each slides}}
        {{dynamictemplate this.template this.data}}
    {{/each}}
    

提交回复
热议问题