How to append html into section in dust.js?

╄→尐↘猪︶ㄣ 提交于 2019-12-11 20:09:28

问题


How do you append html into a section in dust.js? It seems that there isn't a built-in way to do this. Maybe some kind of streaming block could be used to achieve this? Another solution might be a dustjs-helper which would find a section and append into it.

I need this functionality to add scripts and styles in the head of the html document, when including other templates into the parent template.

Any ideas how to approach this problem? I'll also accept solutions which use bodies or blocks instead of sections.


回答1:


If I understand you right, you want some kind of block which you can use to inject dynamic content into!? You could indeed write a helper to do that.

Let's say you have a template and define a custom helper

{@append someParam="someValue"/}

Then you write the helper (described here)

(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>');
        });
    };
}();

If you need a block like

{@append}
    some string
{/append}

You need to modify the helper a bit (thanks to 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;

Which should give you: 'This is some string we wrapped!'

Note: Not tested, just written ^^

Hope this helps though, cheers.



来源:https://stackoverflow.com/questions/19858271/how-to-append-html-into-section-in-dust-js

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