How to pass partials to a Dust.js template

为君一笑 提交于 2019-12-06 15:18:28

If you have a template named someTemplate you can include it in another template using {>someTemplate/}. You can assign context with {>someTemplate:someContext/} and pass inline parameters with {>someTemplate some_param="A parameter"/}. Example:

<h1>{heading}</h1>
<p>{article}</p>
{>someTemplate/}

If you want to use blocks (they have the following syntax {+blockName/} or {+blockName}Default block content{/blockName} then you must define a template with the block, then include that template as a partial, then override the block. Example template with name "someTemplate":

<h1>{heading}</h1>
<p>{article}</p>
{+someBlock/}

Then override the block like so:

{>someTemplate/}
{<someBlock}
    My custom block content.
{/someBlock}

EDITS:

To customise the block outside of the template, create a context using dust.makeBase. This context object can be passed to dust.render in place of your templateData (dust does this internally anyway). Then add a block to the context using context.shiftBlocks with the argument being a hash with the blocks you want to override. Example:

var context = dust.makeBase(templateData).shiftBlocks({
    someblock: function (chunk, context) {
        return chunk.write('my new block content');
    }
});

dust.render('myTemplate', context, function (error, html) {
    console.log(html);
});

Some final comments: to be honest, I've not had a need to do this so far. I'd try to do as much with the template syntax as possible so that your templates can be understood on their own. Anyway, I hope this helps.

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