[IMP] app: allow to instantiate templates lazily

With this commit, the templates that are given while instantiating the
App class can be an object with templates not yet parsed (i.e. string,
not Document). This allow to instantiate the App class with templates
that are not yet parsed, and these templates will be parsed only when
needed.

Part of task-id 3601257
This commit is contained in:
Pierre Rousseau
2023-11-29 11:37:56 +01:00
committed by Sam Degueldre
parent a53e42518f
commit 941190dfa8
3 changed files with 38 additions and 2 deletions
+8 -2
View File
@@ -41,7 +41,7 @@ export interface TemplateSetConfig {
dev?: boolean; dev?: boolean;
translatableAttributes?: string[]; translatableAttributes?: string[];
translateFn?: (s: string) => string; translateFn?: (s: string) => string;
templates?: string | Document; templates?: string | Document | Record<string, string>;
} }
export class TemplateSet { export class TemplateSet {
@@ -60,7 +60,13 @@ export class TemplateSet {
this.translateFn = config.translateFn; this.translateFn = config.translateFn;
this.translatableAttributes = config.translatableAttributes; this.translatableAttributes = config.translatableAttributes;
if (config.templates) { if (config.templates) {
this.addTemplates(config.templates); if (config.templates instanceof Document || typeof config.templates === "string") {
this.addTemplates(config.templates);
} else {
for (const name in config.templates) {
this.addTemplate(name, config.templates[name]);
}
}
} }
} }
+13
View File
@@ -57,6 +57,19 @@ exports[`app can configure an app with props 1`] = `
}" }"
`; `;
exports[`app can load templates from an object name-string 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div class=\\"hello\\">hello</div>\`);
return function template(ctx, node, key = \\"\\") {
return block1();
}
}"
`;
exports[`app can mount app in an iframe 1`] = ` exports[`app can mount app in an iframe 1`] = `
"function anonymous(app, bdom, helpers "function anonymous(app, bdom, helpers
) { ) {
+17
View File
@@ -167,4 +167,21 @@ describe("app", () => {
] ]
`); `);
}); });
test("can load templates from an object name-string", async () => {
const templates = {
hello: `<div class="hello">hello</div>`,
world: `<div>world</div>`,
};
class SomeComponent extends Component {
static template = "hello";
}
const app = new App(SomeComponent, { templates });
await app.mount(fixture);
expect(fixture.querySelector(".hello")).toBeDefined();
// Only the "hello" template is used, so the "world" template is not yet loaded
expect(Object.keys(app.templates)).toEqual(["hello"]);
expect(Object.keys(app.rawTemplates)).toEqual(["hello", "world"]);
});
}); });