Hamsteriffic Hamsteriffic - 3 months ago 60
Javascript Question

How to make Docxtemplater.js work on browser without any knowledge of Node/Browserify/npm and such?

I want to make Docxtemplater.js work on browser.

Unfortunately, I have no knowledge of these things as Node.js, Browserify.js, "npm", "bower", and that kind of thing that appear in all those nice and cool modern JS libraries. I want to learn about them, but in the future... Right now I just want to make this Docxtemplater.js work.

In the bottom of the page, they show how to do it with npm, but I don't want that, so I went to the Quickstart In The Browser. I must have done something wrong, because it is not working.

This is what I did:


  • I created a file called
    testpage.html
    with the following content:

    <html><body>
    <script src="build/docxtemplater.js"></script>
    <script src="vendor/FileSaver.min.js"></script>
    <script src="vendor/jszip-utils.js"></script>
    <script>
    var loadFile = function(url,callback) {
    JSZipUtils.getBinaryContent(url,callback);
    }
    loadFile("examples/tagExample.docx", function(err, content) {
    if (err) { throw e };
    doc = new Docxtemplater(content);
    doc.setData({
    "first_name": "Hipp",
    "last_name": "Edgar",
    "phone": "0652455478",
    "description": "New Website"
    }); //set the templateVariables
    doc.render(); //apply them (replace all occurences of {first_name} by Hipp, ...)
    out=doc.getZip().generate({type:"blob"}); //Output the document using Data-URI
    saveAs(out,"output.docx");
    });
    </script>
    </body></html>

  • I created a folder
    build
    and put the file
    docxtemplater.js
    there, downloaded from here, specifically the raw file docxtemplater.v2.1.3.min.js (of course I renamed it to
    docxtemplater.js
    ).

  • I created a folder
    vendor
    and put the files
    FileSaver.min.js
    and
    jszip-utils.js
    there, both files taken from here.

  • I created a folder
    examples
    and put the file
    tagExample.docx
    there, taken from here.



That is precisely what I did. I did not add any other files or folders, or anything.

Then, I opened the file
testpage.html
with my Firefox 47.0.1 on Windows 7. With the console open, I get the following error message:

ReferenceError: Docxtemplater is not defined
- on this line:
doc = new Docxtemplater(content);


What's wrong? How to fix this?


Answer

I found out the solution: just replace new Docxtemplater(content) with new Docxgen(content).

This happens only when downloading the JS build directly from github, as I did.

I opened an issue about it, and now this is properly documented in Readme.md:

If you download the JS from there, you should use new Docxgen() instead of new Docxtemplater(), because I do not want to bring in a breaking change on a minor version change in the docxtemplater-build repository.

It seems that "Docxgen" was the old name of the library, now renamed to "Docxtemplater".