Search code examples
dust.js

dustjs rendering client-side not working


Using dustjs for templating engine within Expressjs 4. Want to render the template client-side when user fills out a form and clicks a search button using xhr. Everything seems to go fine so far as getting the json from xhr call but dust.render does not render the result.

Here is the dust template on the page:


    <script id="result-template">
    // extra table tags removed for brevity
    {#search_results}
      {fname}
      {lname}
      {accountId}
      {email}
      {status}
     {/search_results}
    </script>
    <div id="output">

Below is the js/jquery in an external js file making the xhr call to server-side. Inside the success callback is where I'm trying to render the result from the call, basically user fills-in a search form and clicks submit:

$(document).ready(function () {
  $('#main').on('click', '#search-btn', function (e) {
   e.preventDefault();
   $.ajax({
     url: '/support/search/ah',
     type: "post",
     headers: {token: sessionStorage.getItem('somekey')},
     data: {'phone': $('#mobile').val(),
            'email': $('#email').val(),
            'fname': $('#fname').val(),
            'lname': $('#lname').val()
            },
    success: function (data, textStatus, request) {
      var source   = $("#result-template").html();
      var compiled = dust.compile(source, "intro");
      dust.loadSource(compiled);
      dust.render("intro", data, function(err, out) {
        $("#output").html(out);
        $('#search-result').dataTable();
      });
   },
   error: function (data, textStatus, request) {
   // handle error
   })  
})

xhr call is successful, and I can see that 'data' variable contains the json with values, however, I'm not able to render them using dust.render and there are no js errors being observed when the page loads or when the results come back.

Here is the json result from xhr call:

{"search_results":[{"fname":"Duke", "lname":"Wellington","accountId":"007","email":"duke_wellington","status":"Breathing"}]};

I tried the same template with same json results at atakdubya.github.io replacing its array example and it works fine.

If anyone can point out what I'm doing wrong it would be immensely appreciated.


Solution

  • Depending on your browser, you can't have a script tag with no type or it will be interpreted as Javascript, and Dust isn't valid Javascript.

    Try adding type="text/dust" to your script tag. This JSFiddle works for me.

    http://jsfiddle.net/Lutr4h2e/1/