From 4a889b7b6bf3f12eedb6ed960e44301ccfda1c32 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?G=C3=A9ry=20Debongnie?= Date: Mon, 24 Jun 2019 22:41:02 +0200 Subject: [PATCH] [IMP] qweb: add option to allow duplicate templates --- doc/qweb.md | 4 +++- src/qweb_core.ts | 5 ++++- tests/qweb.test.ts | 13 +++++++++---- 3 files changed, 16 insertions(+), 6 deletions(-) diff --git a/doc/qweb.md b/doc/qweb.md index f046cfdf..a6bc9f02 100644 --- a/doc/qweb.md +++ b/doc/qweb.md @@ -95,12 +95,14 @@ It's API is quite simple: const qweb = new owl.QWeb(TEMPLATES); ``` -- **`addTemplate(name, xmlStr)`**: add a specific template. +- **`addTemplate(name, xmlStr, allowDuplicate)`**: add a specific template. ```js qweb.addTemplate("mytemplate", "
hello
"); ``` + If the optional `allowDuplicate` is set to `true`, then `QWeb` will simply return whenever a template is added for a second time. Otherwise, `QWeb` will crash. + - **`addTemplates(xmlStr)`**: add a list of templates (identified by `t-name` attribute). diff --git a/src/qweb_core.ts b/src/qweb_core.ts index db8935e7..f6605035 100644 --- a/src/qweb_core.ts +++ b/src/qweb_core.ts @@ -173,7 +173,10 @@ export class QWeb extends EventBus { * Add a template to the internal template map. Note that it is not * immediately compiled. */ - addTemplate(name: string, xmlString: string) { + addTemplate(name: string, xmlString: string, allowDuplicate?: boolean) { + if (allowDuplicate && name in this.templates) { + return; + } const doc = parseXML(xmlString); if (!doc.firstChild) { throw new Error("Invalid template (should not be empty)"); diff --git a/tests/qweb.test.ts b/tests/qweb.test.ts index d34187b8..369cf26b 100644 --- a/tests/qweb.test.ts +++ b/tests/qweb.test.ts @@ -25,13 +25,15 @@ describe("static templates", () => { }); test("simple dynamic value", () => { - qweb.addTemplate("test", ""); - expect(renderToString(qweb, "test", {text: "hello vdom"})).toBe("hello vdom"); + qweb.addTemplate("test", ''); + expect(renderToString(qweb, "test", { text: "hello vdom" })).toBe( + "hello vdom" + ); }); test("simple string, with some dynamic value", () => { - qweb.addTemplate("test", "hello "); - expect(renderToString(qweb, "test", {text: "vdom"})).toBe("hello vdom"); + qweb.addTemplate("test", 'hello '); + expect(renderToString(qweb, "test", { text: "vdom" })).toBe("hello vdom"); }); test("empty div", () => { @@ -71,6 +73,9 @@ describe("error handling", () => { test("cannot add twice the same template", () => { qweb.addTemplate("test", ``); + expect(() => qweb.addTemplate("test", "
", true)).not.toThrow( + "already defined" + ); expect(() => qweb.addTemplate("test", "
")).toThrow("already defined"); });