Skip to content

Commit

Permalink
fix docx rendering with handlebars partials
Browse files Browse the repository at this point in the history
fix #1047
  • Loading branch information
bjrmatos committed Apr 11, 2023
1 parent fbfc52f commit d254c48
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 0 deletions.
11 changes: 11 additions & 0 deletions packages/jsreport-docx/lib/processDocx.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,20 @@ module.exports = (reporter) => async (inputs, req) => {

const contentToRender = filesToRender.map(f => {
const xmlStr = new XMLSerializer().serializeToString(f.doc, undefined, (node) => {
// we need to decode the xml entities for the attributes for handlebars to work ok
if (node.nodeType === 2 && node.nodeValue && node.nodeValue.includes('{{')) {
const str = new XMLSerializer().serializeToString(node)
return decodeXML(str)
} else if (
// we need to decode the xml entities in text nodes for handlebars to work ok with partials
node.nodeType === 3 && node.nodeValue &&
(node.nodeValue.includes('{{>') || node.nodeValue.includes('{{#>'))
) {
const str = new XMLSerializer().serializeToString(node)

return str.replace(/{{#?>/g, (m) => {
return decodeXML(m)
})
}

return node
Expand Down
Binary file added packages/jsreport-docx/test/partial.docx
Binary file not shown.
28 changes: 28 additions & 0 deletions packages/jsreport-docx/test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,34 @@ describe('docx', () => {
])
})

it('handlebars-partials', async () => {
const result = await reporter.render({
template: {
engine: 'handlebars',
recipe: 'docx',
helpers: `
const h = require('handlebars')
h.registerPartial('test', '{{name}}')
`,
docx: {
templateAsset: {
content: fs.readFileSync(
path.join(__dirname, 'partial.docx')
)
}
}
},
data: {
name: 'John'
}
})

fs.writeFileSync('out.docx', result.content)
const text = (await extractor.extract(result.content)).getBody()
text.should.containEql('Hello world John')
})

it('invoice', async () => {
const result = await reporter.render({
template: {
Expand Down

0 comments on commit d254c48

Please sign in to comment.