Search code examples
sails.jsdust.js

Dustjs helper for frontend


So I am using Dustjs on Sailsjs for my project.

I am rendering the first page on the server, and then use the same template client-side.

Problem: My template contains a global sails service which doubles as a dustjs helper:

{#sails.services.globalutils.hyphenator str=title/}

But, on the client-side, I am unable to uyse this service. How can I export this service to the client without going for a JS solution? Can it be bundled with the dustjs template ?


Solution

  • A {#section} signals that Dust should look in the context provided to dust.render(). So as long as the hyphenator function doesn't have server-side dependencies, you can just bring it along in your client-side context. Sails services are just Javascript modules in the api/services folder, so try requireing the relevant module, grabbing its hyphenator property, and passing that along to the client to use in the client's render call.

    {
      "sails": {
        "services": {
          "globalutils": {
            "hyphenator": function(chunk, context, bodies, params) {
              // do some hyphenation
            }
          }
        }
      }
    }
    

    Of course, if hyphenator has logic that relies on the server, you can't just move it to the client. You could expose a server-side API that your script calls, and couple that with chunk.map to create an asynchronous Dust block.