如何将 html 附加到 dust.js 中的部分

How to append html into section in dust.js?

本文关键字:js dust html      更新时间:2023-09-26

如何将html附加到dust.js部分中?似乎没有内置的方法可以做到这一点。也许可以使用某种流块来实现这一点?另一种解决方案可能是 dustjs 助手,它会找到一个部分并附加到其中。

当将其他模板包含在父模板中时,我需要此功能在 html 文档的头部添加脚本和样式。

有什么想法可以解决这个问题吗?我还将接受使用主体或块而不是部分的解决方案。

如果我

理解正确,你想要某种可以用来注入动态内容的块!?你确实可以写一个助手来做到这一点。

假设您有一个模板并定义了一个自定义帮助程序

{@append someParam="someValue"/}

然后你写帮助程序(描述在这里)

(function () {
    'use strict';
    // load dust if not already there
    dust = require('dustjs-linkedin');
    // load helpers if not already done
    require('dustjs-helpers')
    // create our custom helper 
    // (note that 'append' is the name of the helper, as used in the template)
    dust.helpers.append = function (chunk, context, bodies, params) {
        // create a new chunk and map it to make it async
        // you could also do `return chunk.write('somehtml')` if you use it sync
        return chunk.map(function (chunk) {
            chunk.end('<div>' + params.someParam + '</div>');
        });
    };
}();

如果你需要一个像

{@append}
    some string
{/append}

您需要稍微修改一下帮助程序(感谢 odd.ness.io):

if (bodies.block) {
    return chunk.capture(bodies.block, context, function(string, chunk) {
        chunk.end('This is ' + string + ' we wrapped!');
    });
}
// If there's no block, just return the chunk
return chunk;

这应该给你:"这是我们包裹的绳子!

注意:未测试,只是编写^^

希望这有帮助,干杯。