allow dynamic expressions in t-props directive

This commit is contained in:
Géry Debongnie
2019-01-28 12:03:59 +01:00
parent 3906c7eee1
commit 2b27249136
2 changed files with 63 additions and 1 deletions
+17 -1
View File
@@ -689,7 +689,7 @@ const refDirective: Directive = {
const widgetDirective: Directive = {
name: "widget",
priority: 100,
atNodeEncounter({ ctx, value, node }): boolean {
atNodeEncounter({ ctx, value, node, qweb }): boolean {
ctx.rootContext.shouldDefineOwner = true;
let dummyID = ctx.generateID();
let defID = ctx.generateID();
@@ -697,6 +697,22 @@ const widgetDirective: Directive = {
ctx.addLine(`let _${dummyID}_index = c${ctx.parentNode}.length;`);
ctx.addLine(`c${ctx.parentNode}.push(_${dummyID});`);
let props = node.getAttribute("t-props");
if (props) {
props = props.trim();
if (props[0] === "{" && props[props.length - 1] === "}") {
const innerProp = props
.slice(1, -1)
.split(",")
.map(p => {
let [key, val] = p.split(":");
return `${key}: ${qweb._formatExpression(val)}`;
})
.join(",");
props = "{" + innerProp + "}";
} else {
props = qweb._formatExpression(props);
}
}
let widgetID = ctx.generateID();
ctx.addLine(
`let _${widgetID} = new context.widgets['${value}'](owner, ${props});`
+46
View File
@@ -517,3 +517,49 @@ describe("composition", () => {
expect(children(widget)[0].env).toBe(env);
});
});
describe("props evaluation (with t-props directive)", () => {
test("explicit object prop", async () => {
class Parent extends Widget<WEnv> {
name = "a";
template = `<div><t t-widget="child" t-props="{value: state.val}"/></div>`;
widgets = { child: Child };
state = { val: 42 };
}
class Child extends Widget<WEnv> {
template = `<span><t t-esc="state.someval"/></span>`;
state: { someval: number };
constructor(parent: Parent, props: { value: number }) {
super(parent);
this.state = { someval: props.value };
}
}
const widget = new Parent(env);
await widget.mount(fixture);
expect(fixture.innerHTML).toBe("<div><span>42</span></div>");
});
test("object prop value", async () => {
class Parent extends Widget<WEnv> {
name = "a";
template = `<div><t t-widget="child" t-props="state"/></div>`;
widgets = { child: Child };
state = { val: 42 };
}
class Child extends Widget<WEnv> {
template = `<span><t t-esc="state.someval"/></span>`;
state: { someval: number };
constructor(parent: Parent, props: { val: number }) {
super(parent);
this.state = { someval: props.val };
}
}
const widget = new Parent(env);
await widget.mount(fixture);
expect(fixture.innerHTML).toBe("<div><span>42</span></div>");
});
});