RazorExpress icon indicating copy to clipboard operation
RazorExpress copied to clipboard

What to do after raz.render

Open oskar-anderson opened this issue 3 years ago • 0 comments

The guide didn't mention what to do after let html = raz.render(template); So I had to figure thing out myself.

I tried to run the sample provide. I downloaded it and ran

npm install raz --save
npm install express --save
node server.js

But I get a "A template compilation error occured" error.

So I figured out you can do this:

    function render(template, data = {}, targetElementId) {
        template = new DOMParser().parseFromString(template, "text/html").documentElement.textContent;  //decode html 
        let rendered = raz.render(template, data);
        let frag = parsePartialHtml(rendered);
        fixParsedScriptsToExecute(frag);
        document.getElementById(targetElementId).innerHTML = "";
        document.getElementById(targetElementId).appendChild(frag);

/**
     *
     * @@param { string } html
     */
    function parsePartialHtml(html) {
        let doc = new DOMParser().parseFromString(html, "text/html");
        let frag = document.createDocumentFragment();

        if (doc.childNodes.length !== 0) {
            frag.appendChild(doc.childNodes[0]);
        } else {
            throw Error('unexpected! doc.childNodes.length is ' + doc.childNodes.length);
        }
        return frag;
    }


    /**
     *
     * @@param { DocumentFragment } frag
     */
    function fixParsedScriptsToExecute(frag) {
        let scripts = frag.querySelectorAll('script');

        for (let i = 0; i < scripts.length; i++) {
            let script = scripts[i];
            let fixedScript = document.createElement('script');
            fixedScript.type = script.type;
            fixedScript.innerHTML = script.innerHTML;

            script.parentNode.replaceChild(fixedScript, script);
        }
    }

I don't really understand what is going on (this is based on code snippets from StackOverflow), but it does work. Is this a correct approach? Would you extend the guide to show what to do after raz.render() in case this is a bad approach.

oskar-anderson avatar Dec 24 '21 20:12 oskar-anderson