pub struct Template<S: PackageSource = ZipPackageSource> { /* private fields */ }Expand description
A DOCX template ready for rendering.
The template is loaded once and can be rendered multiple times with different contexts. Parsing and validation happen at load time.
The type parameter selects the package source and defaults to
ZipPackageSource, so Template on its own is the file backed template
and Template<InMemoryPackageSource> is the in memory one.
§Examples
use docx_templating::Template;
use serde_json::json;
let template = Template::from_path("template.docx")?;
let rendered = template.render(json!({"name": "Ada"}))?;
rendered.write_to_file("output.docx")?;§Sharing
A loaded template is immutable and implements Send and Sync, so it can
be shared across threads:
use docx_templating::Template;
use std::sync::Arc;
let template = Arc::new(Template::from_path("template.docx")?);
let handles: Vec<_> = (0..4)
.map(|_| {
let template = Arc::clone(&template);
std::thread::spawn(move || {
template.render(serde_json::json!({ "name": "Ada" }))
})
})
.collect();
for handle in handles {
let rendered = handle.join().expect("worker panicked")?;
rendered.write_to_file("output.docx")?;
}Implementations§
Source§impl Template<ZipPackageSource>
impl Template<ZipPackageSource>
Sourcepub fn from_path(path: impl AsRef<Path>) -> Result<Self>
pub fn from_path(path: impl AsRef<Path>) -> Result<Self>
Load a template from a file path.
§Errors
Returns error if:
- File cannot be opened
- ZIP is invalid
- Required DOCX parts are missing
- Template syntax is invalid
Sourcepub fn from_reader(reader: impl Read) -> Result<Self>
pub fn from_reader(reader: impl Read) -> Result<Self>
Load a template from a reader.
§Errors
Returns error if:
- Reader cannot be read
- ZIP is invalid
- Required DOCX parts are missing
- Template syntax is invalid
Sourcepub fn from_bytes(bytes: impl Into<Vec<u8>>) -> Result<Self>
pub fn from_bytes(bytes: impl Into<Vec<u8>>) -> Result<Self>
Load a template from raw bytes.
Accepts anything that converts into a Vec<u8>, so Vec<u8>, a byte
slice and a byte array all work.
§Errors
Returns error if:
- Bytes are not a valid ZIP
- Required DOCX parts are missing
- Template syntax is invalid
Source§impl<S: PackageSource> Template<S>
impl<S: PackageSource> Template<S>
Sourcepub fn from_source(source: S) -> Result<Self>
pub fn from_source(source: S) -> Result<Self>
Create a template from any package source.
This is the main initialization path. It:
- Validates the package structure
- Reads word/document.xml
- Parses the part into the document tree
- Binds the template syntax to the tree
Sourcepub fn with_options(self, options: TemplateOptions) -> Self
pub fn with_options(self, options: TemplateOptions) -> Self
Set rendering options.
§Examples
let template = Template::from_path("template.docx")?
.with_options(TemplateOptions::default()
.missing_value_policy(MissingValuePolicy::Empty));Sourcepub fn diagnostic(&self, error: &Error) -> Diagnostic
pub fn diagnostic(&self, error: &Error) -> Diagnostic
Build a compiler style diagnostic for an error from this template.
Use it for the errors Template::render returns. The diagnostic
shows the message, the part, and a help line naming the next step.
Errors raised while loading have no template to point at, because
loading stopped. Use diagnose with the original
package bytes for those.
§Examples
let template = Template::from_path("template.docx")?;
if let Err(error) = template.render(serde_json::json!({})) {
eprintln!("{}", template.diagnostic(&error));
}Sourcepub fn render(&self, context: impl IntoContext) -> Result<RenderedDocument>
pub fn render(&self, context: impl IntoContext) -> Result<RenderedDocument>
Render the template with the given context.
Accepts a crate::Context, a serde_json::Value such as the result of
serde_json::json!, or a reference to any serde::Serialize value.
§Errors
Returns error if:
- The context cannot be serialized to JSON
- Context resolution fails
- Missing variables (with
MissingValuePolicy::Error) - Applying the render plan fails
- ZIP writing fails
§Examples
#[derive(Serialize)]
struct Invoice {
total: u32,
}
let template = Template::from_path("template.docx")?;
let invoice = Invoice { total: 42 };
let rendered = template.render(&invoice)?;Sourcepub fn render_to_writer(
&self,
context: impl IntoContext,
writer: impl Write + Seek,
) -> Result<()>
pub fn render_to_writer( &self, context: impl IntoContext, writer: impl Write + Seek, ) -> Result<()>
Render the template into an existing writer.
This is Template::render without the intermediate Vec<u8>: the
package is written straight to writer. Use it for a file, a socket, or
any other Write + Seek destination.
The rendered XML is still built in memory, because the plan is applied to a copy of the parsed tree. What this method avoids is holding the finished ZIP in memory as well.
§Errors
Returns the same errors as Template::render, plus any error the
writer raises.
§Examples
let template = Template::from_path("template.docx")?;
let file = std::fs::File::create("output.docx")?;
template.render_to_writer(serde_json::json!({ "name": "Ada" }), file)?;