javascript - 如何在hbs中渲染JS函数?

标签 javascript node.js handlebars.js

我正在尝试使用 Handlebars 在我的网站中实现 Google 登录功能。

我想将我的脚本包含在一个文件中,并在 https://apis.google.com/js/api:client.js? 加载时加载它,因为它创建了一个对象 gapi 我在我的 js 中使用。

问题是,handlebars 没有提供任何加载 js 文件的帮助。 我尝试使用帮助程序,但问题是 gapi 在注册的帮助程序中未定义,因为 gapi 在加载客户端库时加载。

我尝试这样做

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

但是错误依然存在,有没有办法在hbs中加载js文件?或者我只需将我的代码放入脚本标记本身?

最佳答案

在我看来,您将 Handlebars 与其他东西混淆了。 不要做这样的事情,尝试做这样的事情:

  • 在 html 中正常加载您的 api。
  • 一旦加载,您就可以调用您的 Handlebars 部件(例如 jquery 有一个很好的 on-ready 函数)。
  • 处理完 Handlebars 结果后,将其注入(inject)到您的 html 中。
  • 如果您需要启动另一个脚本,请稍后再执行

这是一个例子:

$(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>

关于javascript - 如何在hbs中渲染JS函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48908892/

相关文章:

javascript - 仅当使用 jQuery 的 html() 内部存在 <img/> 标记时获取元素内部文本

node.js - NODE_ENV=development 在 .bash_profile 中设置但在代码中使用时未定义

AngularJS 和 Handlebars - 两者都需要或不需要

c# - 将奇怪的日期格式转换为短 DateTime

javascript - 为什么 setAttribute 在 jQuery 的 attr 不起作用时起作用

javascript - 使用 JS 在 HTML 中操作 SVG

reactjs - React.js 模拟 Handlebars 条件语句的方法

javascript - 拆分数组数组

node.js - MarkLogic 8 - XQuery 将大型结果集有效写入文件

javascript - 使用 Javascript 查找并替换 HTML iframe "srcdoc"属性中的文本