问题
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