How do you include a raw, uncompiled partial in dust.js?

南楼画角 提交于 2020-01-07 03:07:07

问题


I have dust working reasonably well, but I'd like to be able to include a file, such as a css file, without compiling and rendering it.

It seems like maybe I need to create an onLoad handler that loads the file and registers the content directly.

Is there a way to do this within dust already?


回答1:


You can take advantage of Dust's native support for streams and promises to make file inclusion really nice. The exact implementation depends on whether you're running Dust on the server or the client, but the idea is the same.

Write a helper that loads the file and returns a Stream or Promise for the result. Dust will render it into the template asynchronously, so doing file I/O won't block the rest of the template from processing.

For simplicity, I'll write a context helper, but you could also make this a Dust global helper.

{
  "css": function(chunk, context, bodies, params) {
    // Do some due diligence to sanitize paths in a real app
    var cssPrefix = '/css/';
    var path = cssPrefix + context.resolve(params.path);
    return $.get(path);
  }
}

Then use it like this:

{#css path="foo/bar.css"}{.}{/css}

Or a streamy version for the server:

{
  "css": function(chunk, context, bodies, params) {
    // Do some due diligence to sanitize paths in a real app
    var cssPrefix = '/css/';
    var path = cssPrefix + context.resolve(params.path);
    return fs.createReadStream(path, "utf8");
  }
}


来源:https://stackoverflow.com/questions/34406701/how-do-you-include-a-raw-uncompiled-partial-in-dust-js

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!