4

如何从 Nunjucks 扩展中设置变量?例如,这里是一个模板和一个扩展。该x变量应该只在sample块内可见。

模板:

{% sample %}
{{ x }}
{% endsample %}

扩大:

function SampleExtension() {
  this.tags = ['sample'];

  this.parse = function(parser, nodes, lexer) {
    var tok = parser.nextToken();
    var args = parser.parseSignature(null, true);

    parser.advanceAfterBlockEnd(tok.value);

    var body = parser.parseUntilBlocks('endsample');

    parser.advanceAfterBlockEnd();

    return new nodes.CallExtension(this, 'run', args, [ body ]);
  };

  this.run = function(context, args, body) {
    // I'm guessing I need to mess with the context variable here?

    var ret = new nunjucks.runtime.SafeString(body());

    return ret;
  };
}
4

0 回答 0