Skip to main content

Template

Struct Template 

Source
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>

Source

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
Source

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
Source

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>

Source

pub fn from_source(source: S) -> Result<Self>

Create a template from any package source.

This is the main initialization path. It:

  1. Validates the package structure
  2. Reads word/document.xml
  3. Parses the part into the document tree
  4. Binds the template syntax to the tree
Source

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));
Source

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));
}
Source

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)?;
Source

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)?;

Trait Implementations§

Source§

impl<S: PackageSource + Debug> Debug for Template<S>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<S = ZipPackageSource> !RefUnwindSafe for Template<S>

§

impl<S = ZipPackageSource> !UnwindSafe for Template<S>

§

impl<S> Forget for Template<S>

§

impl<S> Freeze for Template<S>
where S: Freeze, *const u8 is !null: Freeze, PhantomData<(String, Arc<dyn Fn(&Value, Option<&str>) -> Result<Value, FilterError> + Sync + Send>)>: Freeze, PhantomData<u8>: Freeze, PhantomData<Node>: Freeze, PhantomData<BoundParagraph>: Freeze, PhantomData<BoundRow>: Freeze, PhantomData<Block>: Freeze, PhantomData<InlineContent>: Freeze, PhantomData<SecondaryPart>: Freeze,

§

impl<S> Move for Template<S>

§

impl<S> Send for Template<S>
where S: Send, RawTable<(String, Arc<dyn Fn(&Value, Option<&str>) -> Result<Value, FilterError> + Sync + Send>)>: Send, RawVecInner: Send, BoxRaw<Expression>: Send,

§

impl<S> Sync for Template<S>
where S: Sync, RawTable<(String, Arc<dyn Fn(&Value, Option<&str>) -> Result<Value, FilterError> + Sync + Send>)>: Sync, RawVecInner: Sync, BoxRaw<Expression>: Sync,

§

impl<S> Unpin for Template<S>
where S: Unpin, *const u8 is !null: Unpin, Arc<dyn Fn(&Value, Option<&str>) -> Result<Value, FilterError> + Sync + Send>: Unpin, Box<Expression>: Unpin,

§

impl<S> UnsafeUnpin for Template<S>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.