How do I load different partials dynamically using handlebars templates?

后端 未结 3 665
慢半拍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:53

    When Handlebars.partials[] returns a raw string it means the partial is not compiled.

    I am not sure but my best guess is that Handlebars compiles the partial internally when it compiles the template which includes the partial. So when you use a helper to include a partial then Handlebars doesn't recognize it and it will not be compiled.

    You can compile the partial yourself. Don't forget to register the compiled partial or you end up compiling every time the partial is required, which hurts performance. Something like this should work.

    var template = Handlebars.partials['templatename'],
        fnTemplate = null;
    
    if (typeof template === 'function') {
      fnTemplate = template;
    } else {
      // Compile the partial
      fnTemplate = Handlebars.compile(partial);
      // Register the compiled partial
      Handlebars.registerPartial('templatename', fnTemplate);  
    }
    
    return fnTemplate(context);
    

提交回复
热议问题