fedor.belov
fedor.belov

Reputation: 23323

Does handlebars.js support promises?

Some properties of my model should be loaded asynchronously (implemented by promises). I don't want to wait it - I want to render it right now and partially update it when promises will be resolved. Does handlebars.js support it?

Upvotes: 2

Views: 2813

Answers (2)

chendu
chendu

Reputation: 828

I think i can propose a workaround to get the async (or promises) to (seem to) work. Below is the example. Essentially this is what i am doing

  1. First return a div with an unique Id (i am using namespace + auto increment here)
  2. Do your processing (ajax or what ever slowly). Once done replace the innerHTML of the div in step1 with new data by accessing it via the unique id

code below. Observe the tripple bracket ({{{ }}}). This is to make sure generated HTML is not escaped


<script id="handlebars-demo" type="text/x-handlebars-template">
   <div>
     -->> {{{functionName "functionParam" }}} <<-- 
   </div>
</script>

<div id="output"  />

<script>
    window.id=0;
    Handlebars.registerHelper('functionName',  function(funcParam ){
            let tempId = "my_namespace_" + window.id++;
            $.post("https://something.com/abc").done(function(data){
                        $("#"+tempId ).html(data.something);
                    }
                )
            return '<div id='+tempId+'>loading</div>'
        });


    var template = document.getElementById("handlebars-demo").innerHTML;
    var templateScript = Handlebars.compile(template);
    var context = { };
    var html = templateScript(context);
    document.getElementById("output").innerHTML= html;
</script>

Upvotes: 0

Digitalkapitaen
Digitalkapitaen

Reputation: 2423

Handlebars does not support async. This makes it impossible to use Promises for expressions and helpers. You could use await but this suspends execution, so no rendering takes place until the Promise is settled. Other templating frameworks like dust.js offer async functionality.

Upvotes: 1

Related Questions