Docx-templates
Template-based docx report creation.
Why?
- Write documents naturally using Word, just adding some commands where needed for dynamic contents
- Express your data needs (queries) in the template itself (
QUERY
command), in whatever query language you want (e.g. in GraphQL). This is similar to the Relay way™: in Relay, data requirements are declared alongside the React components that need the data - Execute JavaScript snippets (
EXEC
, or !
for short) - Insert the result of JavaScript snippets in your document (
INS
, or =
for short) - Add loops with
FOR
/END-FOR
commands, with support for table rows, nested loops, and JavaScript processing of elements (filter, sort, etc) - Define custom aliases for some commands (
ALIAS
) — useful for writing table templates! - Run all JavaScript in a separate Node VM for security
- Include literal XML
Contributions are welcome!
Installation
$ npm install docx-templates
...or using yarn:
$ yarn add docx-templates
Usage
API
Here is a (contrived) example, with report data injected directly as an object:
import createReport from 'docx-templates';
createReport({
template: 'templates/myTemplate.docx',
output: 'reports/myReport.docx',
data: {
name: 'John',
surname: 'Appleseed',
},
});
This will create a report based on the input data at the specified path. Some notes:
- All paths are relative to
process.cwd()
- If the output location is omitted, a report will be generated in the same folder as the template
You can also provide a sync or Promise-returning callback function (query resolver) instead of an object data
:
createReport({
template: 'templates/myTemplate.docx',
output: 'reports/myReport.docx',
data: (query) => graphqlServer.execute(query),
});
Your resolver callback will receive the query embedded in the template (in a QUERY
command) as an argument.
Other options (with defaults):
createReport({
cmdDelimiter: '+++',
literalXmlDelimiter: '||',
processLineBreaks: true,
});
Writing templates
You can find several template examples in this repo:
Here is the list of currently supported commands:
QUERY
You can use GraphQL, SQL, whatever you want: the query will be passed unchanged to your data
query resolver.
+++QUERY
query getData($projectId: Int!) {
project(id: $projectId) {
name
details { year }
people(sortedBy: "name") { name }
}
}
+++
For the following sections (except where noted), we assume the following dataset:
const data = {
project: {
name: 'docx-templates',
details: { year: '2016' },
people: [
{ name: 'John', since: 2015 },
{ name: 'Robert', since: 2010 },
]
},
};
INS
(=
)
Inserts the result of a given (JavaScript) snippet:
+++INS project.name+++ (+++INS project.details.year+++)
or...
+++INS `${project.name} (${$details.year})`+++
Note that the last evaluated expression is inserted into the document, so you can include more complex code if you wish:
+++INS
const a = Math.random();
const b = Math.round((a - 0.5) * 20);
`A number between -10 and 10: ${b}.`
+++
You can also use this shorthand notation:
+++= project.name+++ (+++= project.details.year+++)
+++= `${project.name} (${$details.year})`+++
Use JavaScript's ternary operator to implement an if-else structure:
+++= $details.year != null ? `(${$details.year})` : ''+++
EXEC
(!
)
Executes a given JavaScript snippet, just like INS
or =
, but doesn't insert anything in the document. You can use EXEC
, for example, to define functions or constants before using them elsewhere in your template.
+++EXEC
const myFun = () => Math.random();
const MY_CONSTANT = 3;
+++
+++! const ANOTHER_CONSTANT = 5; +++
FOR
and END-FOR
Loop over a group of elements (resulting from the evaluation of a JavaScript expression):
+++FOR person IN project.people+++
+++INS $person.name+++ (since +++INS $person.since+++)
+++END-FOR person+++
Since JavaScript expressions are supported, you can for example filter the loop domain:
+++FOR person IN project.people.filter(person => person.since > 2013)+++
...
FOR
loops also work over table rows:
----------------------------------------------------------
| Name | Since |
----------------------------------------------------------
| +++FOR person IN | |
| project.people+++ | |
----------------------------------------------------------
| +++INS $person.name+++ | +++INS $person.since+++ |
----------------------------------------------------------
| +++END-FOR person+++ | |
----------------------------------------------------------
Finally, you can nest loops (this example assumes a different data set):
+++FOR company IN companies+++
+++INS $company.name+++
+++FOR person IN $company.people+++
* +++INS $person.firstName+++
+++FOR project IN $person.projects+++
- +++INS $project.name+++
+++END-FOR project+++
+++END-FOR person+++
+++END-FOR company+++
ALIAS
(and alias resolution with *
)
Define a name for a complete command (especially useful for formatting tables):
+++ALIAS name INS $person.name+++
+++ALIAS since INS $person.since+++
----------------------------------------------------------
| Name | Since |
----------------------------------------------------------
| +++FOR person IN | |
| project.people+++ | |
----------------------------------------------------------
| +++*name+++ | +++*since+++ |
----------------------------------------------------------
| +++END-FOR person+++ | |
----------------------------------------------------------
Similar projects
-
docxtemplater (believe it or not, I just discovered this very similarly-named project after brushing up my old CS code for docx-templates
and publishing it for the first time!). It provides lots of goodies, but doesn't allow (AFAIK) embedding queries or JS snippets.
-
docx and similar ones - generate docx files from scratch, programmatically. Drawbacks of this approach: they typically do not support all Word features, and producing a complex document can be challenging.
License (MIT)
Copyright (c) Guillermo Grau Panea 2016
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.