alternative to `with` block?

Viewed 373

I am working at a template system comparable to pug (formerly jade). Templates can contain lines of javascript. I solved it using a with block:

- var foo = "bar"  // javascript
p(class=foo)!= bar

is compiled to:

function generatedFromString(context) {
    var result = '';
    with (context) {
        var foo = "bar"  // javascript
        result += '<p class="';
        result += escapeHtml(foo);
        result += '">';
        result += bar;
        result += '</p>';
        return result;
    }
}

This works great. However, I know that with is deprecated and it is even forbidden in strict mode.

So, my next idea was to copy all values of context into global. But I suspect this is even worse, since it pollutes the global namespace and slows down the script.

Apart from that, I don't want to get a ReferenceError when an undeclared variable is used in a template. So it seems that the only solution is to change the output to

        context.foo = "bar"  // javascript

But then I would have to parse the javascript, wich is a lot more effort.

Does anyone know if there is a better solution? Or is it necessary to parse the javascript?

0 Answers
Related