From 700030cc7d362ce33d7bccd77348d1656a0b5ae0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?G=C3=A9ry=20Debongnie?= Date: Fri, 21 Jan 2022 14:15:45 +0100 Subject: [PATCH] [DOC] update changelog renderToString example --- CHANGELOG.md | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 00ef2f79..d8e1c857 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -659,10 +659,14 @@ Also, this can easily be done in userspace, by mounting a component in a div. F export async function renderToString(template, context) { class C extends Component { static template = template; + setup () { + Object.assign(this, context); + } } const div = document.createElement('div'); document.body.appendChild(div); - const component = await mount(C, div); + const app = new App(C); + await app.mount(div); const result = div.innerHTML; app.destroy(); div.remove(); @@ -670,6 +674,30 @@ export async function renderToString(template, context) { } ``` +The function above works for most cases, but is asynchronous. An alternative +function could look like this: + +```js +const { App, blockDom } = owl; +const app = new App(Component); // act as a template repository + +function renderToString(template, context = {}) { + app.addTemplate(template, template, { allowDuplicate: true }); + const templateFn = app.getTemplate(template); + const bdom = templateFn(context, {}); + const div = document.createElement('div') + blockDom.mount(bdom, div); + return div.innerHTML; +} +``` + +This is a synchronous function, so it will not work with components, but it should +be useful for most simple templates. + +Also note that these two examples do not translate their templates. To do that, +they need to be modified to pass the proper translate function to the `App` +configuration. + ### 33. Portal are now defined with `t-portal` Before Owl 2, one could use the `Portal` component by importing it and using it.