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:
    0_1642765756531_upload-d4ce7ceb-d26e-4b97-96c3-c50d8ea0fb5c



  • It seems to work for me
    https://playground.jsreport.net/w/anon/UAx_0t~Y

    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:
    https://playground.jsreport.net/w/Xushlin/6FhQQRdP


  • 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/>'))
    }
    

    https://playground.jsreport.net/w/anon/NITxJTEf



  • thanks.


Log in to reply
 

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