How to render a content contain '&' in the docx?

  • I render a docx template error when a field string contain a character '&' .

    how to fix this problem?

    blow is error picture:

  • It seems to work for me

    Could you share a minimal playground example where it's failing?

  • My template have a custom break line fuction. template like this:
    {{preserveLineBreaks foo}}

    the function as below:

    function preserveLineBreaks(d) {
        return new Handlebars.SafeString(d.replace(/\n/g, '<w:br/>'))
    please see the example here:

  • Handlebars by default escape XML, but when you use Handlebars.SafeString you explicitly say you don't want that.
    The solution would be to explicitly escape the input parameter.

    function escapeXml(unsafe) {
        return unsafe.replace(/[<>&'"]/g, function (c) {
            switch (c) {
                case '<': return '&lt;';
                case '>': return '&gt;';
                case '&': return '&amp;';
                case '\'': return '&apos;';
                case '"': return '&quot;';
    function preserveLineBreaks(d) {
        return new Handlebars.SafeString(escapeXml(d).replace(/\n/g, '<w:br/>'))

  • thanks.

Log in to reply

Looks like your connection to jsreport forum was lost, please wait while we try to reconnect.