Skip to content

Commit dc6b531

Browse files
Merge pull request #21098 from emberjs/nvp/fix-21096-this-template-runtime
[BUGFIX] Add support for `this` in explicit scope for the runtime template compiler.
2 parents 54835c6 + 88432b0 commit dc6b531

2 files changed

Lines changed: 30 additions & 3 deletions

File tree

packages/@ember/-internals/glimmer/tests/integration/components/runtime-template-compiler-explicit-test.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,19 @@ moduleFor(
7272
this.assertStableRerender();
7373
}
7474

75+
async '@test Can use `this` from explicit scope'() {
76+
await this.renderComponentModule(() => {
77+
let state = { cls: 'Hello, world!' };
78+
79+
return template('<div>{{this.cls}}</div>', {
80+
scope: () => ({ this: state }),
81+
});
82+
});
83+
84+
this.assertHTML('<div>Hello, world!</div>');
85+
this.assertStableRerender();
86+
}
87+
7588
async '@test Can use inline if and unless in strict mode templates'() {
7689
await this.renderComponentModule(() => {
7790
return template('{{if true "foo" "bar"}}{{unless true "foo" "bar"}}');

packages/@ember/template-compiler/lib/template.ts

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -270,10 +270,24 @@ function buildEvaluator(options: Partial<EmberPrecompileOptions> | undefined) {
270270
}
271271

272272
return (source: string) => {
273-
const argNames = Object.keys(scope);
274-
const argValues = Object.values(scope);
273+
let hasThis = Object.prototype.hasOwnProperty.call(scope, 'this');
274+
let thisValue = hasThis ? (scope as { this?: unknown }).this : undefined;
275275

276-
return new Function(...argNames, `return (${source})`)(...argValues);
276+
let argNames: string[] = [];
277+
let argValues: unknown[] = [];
278+
279+
for (let [name, value] of Object.entries(scope)) {
280+
if (name === 'this') {
281+
continue;
282+
}
283+
284+
argNames.push(name);
285+
argValues.push(value);
286+
}
287+
288+
let fn = new Function(...argNames, `return (${source})`);
289+
290+
return hasThis ? fn.call(thisValue, ...argValues) : fn(...argValues);
277291
};
278292
}
279293
}

0 commit comments

Comments
 (0)