简体   繁体   English

在页面加载内容后,我可以通过AJAX将内容加载到Handlebars模板中吗?

[英]Can I load content into Handlebars templates via AJAX after the page has loaded content already?

We are in the process of rebuilding an app that provides an account dashboard to customers. 我们正在重建一个为客户提供帐户信息中心的应用程序。

The dashboard page makes lots of web service calls to get data. 仪表板页面会进行大量Web服务调用以获取数据。 In the old app we would use server side rendering to load the page with whatever information we got about the user at login. 在旧的应用程序中,我们将使用服务器端呈现来加载页面,其中包含我们在登录时获得的有关用户的任何信息。 Then we would make AJAX calls to fill in the stuff that would require a bunch of extra backend calls. 然后我们将进行AJAX调用以填充需要大量额外后端调用的内容。 This let the user see some info immediately without having to wait for all of the data to come back before they see anything. 这让用户可以立即看到一些信息,而无需等待所有数据在他们看到任何内容之前返回。

We are considering using Handlebars in the new app. 我们正在考虑在新应用中使用Handlebars I know it's possible to populate a Handlebars template via AJAX. 我知道可以通过AJAX填充Handlebars模板。

Is it possible to interleave content that displays immediately on page load with content that is loaded via AJAX after the page loads? 是否可以将页面加载时立即显示的内容与页面加载后通过AJAX加载的内容交错?

For example, given a component like this: 例如,给定这样的组件:

Imgur

I want for all of the contents of the component to render at page load except for the part in green. 我希望组件的所有内容在页面加载时呈现,除了绿色部分。 That part I want to load via AJAX after page load. 那部分我想在页面加载后通过AJAX加载。 Is this something I can do easily with Handlebars? 这是我用Handlebars可以轻松做到的吗?

Thanks! 谢谢!

You can use format unicorn to do what you want like stack overflow does, example: 您可以使用格式独角兽来执行您想要的堆栈溢出,例如:

Your Html: 你的Html:

    <div id="messageLoader">

    </div>
  </body>
  <script type="text/template" id="templateMessage">
    <h2>{title}</h2>
    <p>{message}</p>
    <br>
    <span><Strong>{sign}</strong><span>
  </script>

Your script: 你的脚本:

String.prototype.formatUnicorn =  function () {
      "use strict";
      var str = this.toString();
      if (arguments.length) {
          var t = typeof arguments[0];
          var key;
          var args = ("string" === t || "number" === t) ?
              Array.prototype.slice.call(arguments)
              : arguments[0];

          for (key in args) {
              str = str.replace(new RegExp("\\{" + key + "\\}", "gi"), args[key]);
          }
      }

      return str;
  };
  var jsonMessage = {title:"Custom Template With Form Unicorn",message:"Stack Overflow Rocks bae !!",sign:"Stan Chacon"};
  let myFirstUnicornTemplate = document.getElementById("templateMessage").text;
  var template = myFirstUnicornTemplate.formatUnicorn(jsonMessage);
  document.getElementById("messageLoader").innerHTML = template;

Edit: Here is jsfiddle working with ajax. 编辑:这是jsfiddle使用ajax。

Hope it helps =) 希望它有帮助=)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM