P.hunter
P.hunter

Reputation: 1365

How to render JS functions in hbs?

i'm trying to implement google sign in functionality in my website using handlebars.

i want to include my script in a file and load it when the https://apis.google.com/js/api:client.js? loads because it creates an object gapi which i use in my js.

The problem is that handlebars doesn't give any help to load js files. i tried using helpers but the problem is that gapi gets undefined in the registered helper as gapi is loaded when client library loads.

i tried doing

<script src="https://apis.google.com/js/api:client.js?onload=after_load"></script>
<script>
function after_load(){     
{{helper_name gapi}}
}
</script>

but still the error persists, is there any way to load a js file in hbs? or i just have to put my code in the script tag itself?

Upvotes: 1

Views: 3979

Answers (1)

Christophe
Christophe

Reputation: 2200

To my mind you're confusing handlebar with something else. Instead of doing such things try to do something like this :

  • load normally your api in your html.
  • once loaded you can call your handlebar part (for example jquery has a nice on ready function).
  • after the handlebar result has been processed inject it in your html.
  • if you need to launch another script then do it afterwards

Here is one example:

$(document).ready(function () {
  var context = { "form" : "<div class='input-container'><div class='label'>User :</div><div class='input'><input type='text' id='username' name='username'></div></div><div class='input-container'><div class='label'>Password :</div><div class='input'><input type='password' id='password' name='password'></div></div>" };
	var source   = $("#sourceTemplate").html();
  var template = Handlebars.compile(source);
  var html    = template(context);
  $("#resultPlaceholder").html(html);
  alert("Load is done place your additional scripts calls here");
});
.input-container { display: inline-block; }
.label { float: left; width: 100px;}
.input { float: left; width: 300px;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.5/handlebars.js"></script>
<script src="https://apis.google.com/js/api:client.js?onload=after_load"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script id="sourceTemplate" type="text/x-handlebars-template">
<div class="container">
  {{{form}}}
</div>
</script>
<br/>
<div id="resultPlaceholder">
</div>

Upvotes: 3

Related Questions