如何将 dustjs-helpers 与 grunt-dust 一起使用?

How to use dustjs-helpers with grunt-dust?

我正在使用 grunt-dust 来编译 dustjs 模板,但现在我 运行 遇到了一个问题,我需要使用 dust helpers(比如 @eq),这显然是 g 运行t-dust完全无视

我已经通过 npm 安装了 dustjs-helpers,但就是不知道如何调整我的 g运行t 配置来处理它们。我简化了它以保留相关部分。

grunt.initConfig( {
    ...

    dust: {
        defaults: {
            files: {
                'public/js/views.js': [ ... directories ... ]
            },
            options: {
                wrapper:  false,
                basePath: 'private/',
                useBaseName: true,
                wrapperOptions: {
                    templatesNamesGenerator: function( options, file ) {
                        // returns an altered template name
                    }
                }
            }
        }
    },

    ...
} )

...

grunt.loadNpmTasks('grunt-dust')

...

grunt.registerTask( ... )

到目前为止,它工作正常并按预期编译了 dustjs 模板。

如何将 dustjs-helpers 包含在 grunt-dust 中?

grunt-dust 编译模板时不需要可用的帮助程序。编译是将模板变成Dust函数的过程,实际上并不会调用helpers。

当你需要可用的dustjs-helpers时渲染。因此,无论您渲染模板如何,您都需要确保助手已附加到您用于渲染的灰尘实例。您只需要求他们即可做到这一点:

let dust = require('dustjs-linkedin');
require('dustjs-helpers'); // helpers autoattach to the `dust` object

dust.render(template, context); // this template will be able to use helpers