我设法在Nunjucks.js中进行了异步自定义扩展,但仍然有一些未解决的问题。以下是其中之一。
如何配置扩展名以使其转义不逃逸。 我的代码看起来像这样。
var nunjucks = require('nunjucks');
module.exports = function CustomExtension() {
this.tags = ['docs'];
this.parse = function(parser, nodes, lexer) {
// parse the args and move after the block end. passing true
// as the second arg is required if there are no parentheses
var args = parser.parseSignature(null, true);
parser.nextToken();
// parse the content until end block
var body = parser.parseUntilBlocks('enddocs');
parser.advanceAfterBlockEnd();
return new nodes.CallExtensionAsync(this, 'run', args, [body]);
};
this.run = function(context, arguments, body, callback) {
var id = body();
somAsyncMagic(id, function(html) {
callback(null, html);
});
};
}
顺便说一下,这段代码在node中使用。如果这样可能会激发某人一些想法。
谢谢
答案 0 :(得分:1)
您可以访问所有内部过滤器,因此答案为cb(null, nunjucks.filters.safe(html));
。
var nunjucks = require('nunjucks');
var MyLoader = nunjucks.Loader.extend({
async: true,
getSource: function(name, callback) {
var res = '...';
callback(err, res);
}
});
var env = new nunjucks.Environment(new MyLoader(), {autoescape: true}); // !
function CustomExtension(cb) {
this.tags = ['docs'];
this.parse = function(parser, nodes, lexer) {
var tok = parser.nextToken();
var args = parser.parseSignature(null, true);
parser.nextToken();
var body = parser.parseUntilBlocks('enddocs');
parser.advanceAfterBlockEnd();
return new nodes.CallExtensionAsync(this, 'run', args, [body], cb);
};
this.run = function(context, args, body, cb) {
var res = env.filters.safe(args + ':' + body()); // prevent escape
cb(null, res);
};
}
env.addExtension('CustomExtension', new CustomExtension());
env.renderString('{% docs "<TEST>" %}"OK"{% enddocs %}', console.log);