How to generate barcode inside mustache template - React/JS

675 views Asked by At

Need to find a way to display a generated barcode inside a mustache template. Currently working with https://github.com/lindell/JsBarcode to generate the barcodes.

The syntax used for JsBarcode has me a bit confused as to how to pass the completed SVG code into the mustache template.

Using JSBarcode I render this barcode: barcode

via JsBarcode using:

 const data = '1234';

    JsBarcode('#barcode', data, {
      format: 'pharmacode',
      lineColor: '#0aa',
      width: 4,
      height: 40,
      displayValue: false,
    });

Which is rendered from the following HTML in the DOM:

<svg id="barcode" width="172px" height="60px" x="0px" y="0px" viewBox="0 0 172 60" xmlns="http://www.w3.org/2000/svg" version="1.1" style="transform: translate(0px, 0px);"><rect x="0" y="0" width="172" height="60" style="fill: rgb(255, 255, 255);"></rect><g transform="translate(10, 10)" style="fill: rgb(0, 170, 170);"><rect x="0" y="0" width="4" height="40"></rect><rect x="12" y="0" width="4" height="40"></rect><rect x="24" y="0" width="12" height="40"></rect><rect x="44" y="0" width="12" height="40"></rect><rect x="64" y="0" width="4" height="40"></rect><rect x="76" y="0" width="12" height="40"></rect><rect x="96" y="0" width="4" height="40"></rect><rect x="108" y="0" width="4" height="40"></rect><rect x="120" y="0" width="12" height="40"></rect><rect x="140" y="0" width="12" height="40"></rect></g></svg>

But in my code, the svg is just

<svg id="barcode" />

How can I pull this rendered svg's HTML without going into the browser console and copy/paste?

To summarize, I'm looking for a way to generate this completed HTML and contain it within a variable inside my component to then pass to a mustache template.

1

There are 1 answers

0
KleinBottleCode On

Found my solution. Using JsBarcode I generate the barcode, then use the following to extract the completed HTML from the generated barcode.

 const ele = document.getElementById('barcode');
      const html = ele.outerHTML;
      const data = { html };
      const json = JSON.stringify(data);

then I can pass the stringified json into the mustache template, and render it per mustache docs (using triple brackets, for anyone in the same boat as me. I.E: {{{barcodeData.html}}}