pub struct Template { /* private fields */ }
Available on crate feature svg only.
Expand description

Template for rendering Transcripts, e.g. into an SVG image.

Available templates

When using a template created with Self::new(), a transcript is rendered into SVG with the text content embedded as an HTML fragment. This is because SVG is not good at laying out multiline texts and text backgrounds, while HTML excels at both. As a downside of this approach, the resulting SVG requires for its viewer to support HTML embedding; while web browsers a priori support such embedding, some other SVG viewers may not.

A template created with Self::pure_svg() renders a transcript into pure SVG, in which text is laid out manually and backgrounds use a hack (lines of text with appropriately colored chars placed behind the content lines). The resulting SVG is supported by more viewers, but it may look incorrectly in certain corner cases. For example, if the font family used in the template does not contain or some chars used in the transcript, the background may be mispositioned.

Snapshot testing functionality produces snapshots using Self::new() (i.e., with HTML embedding); pure SVG templates cannot be tested.

Customization

A custom Handlebars template can be supplied via Self::custom(). This can be used to partially or completely change rendering logic, including the output format (e.g., to render to HTML instead of SVG).

Data supplied to a template is HandlebarsData.

Besides built-in Handlebars helpers (a superset of standard helpers), custom templates have access to the following additional helpers. All the helpers are extensively used by the default template; thus, studying it may be a good place to start customizing. Another example is an HTML template from the crate examples.

Arithmetic helpers: add, sub, mul, div

Perform the specified arithmetic operation on the supplied args. add and mul support any number of numeric args; sub and div exactly 2 numeric args. div also supports rounding via round hash option. round=true rounds to the nearest integer; round="up" / round="down" perform rounding in the specified direction.

{{add 2 3 5}}
{{div (len xs) 3 round="up"}}

Counting lines: count_lines

Counts the number of lines in the supplied string. If format="html" hash option is included, line breaks introduced by <br/> tags are also counted.

{{count_lines test}}
{{count_lines test format="html"}}

Integer ranges: range

Creates an array with integers in the range specified by the 2 provided integer args. The “from” bound is inclusive, the “to” one is exclusive.

{{#each (range 0 3)}}{{@index}}, {{/each}}
{{! Will output `0, 1, 2,` }}

Variable scope: scope

A block helper that creates a scope with variables specified in the options hash. In the block, each variable can be obtained or set using an eponymous helper:

  • If the variable helper is called as a block helper, the variable is set to the contents of the block, which is treated as JSON.
  • If the variable helper is called as an inline helper with the set option, the variable is set to the value of the option.
  • Otherwise, the variable helper acts as a getter for the current value of the variable.
{{#scope test=""}}
  {{test set="Hello"}}
  {{test}} {{! Outputs `Hello` }}
  {{#test}}{{test}}, world!{{/test}}
  {{test}} {{! Outputs `Hello, world!` }}
{{/scope}}

Since variable getters are helpers, not “real” variables, they should be enclosed in parentheses () if used as args / options for other helpers, e.g. {{add (test) 2}}.

Partial evaluation: eval

Evaluates a partial with the provided name and parses its output as JSON. This can be used to define “functions” for better code structuring. Function args can be supplied in options hash.

{{#*inline "some_function"}}
  {{add x y}}
{{/inline}}
{{#with (eval "some_function" x=3 y=5) as |sum|}}
  {{sum}} {{! Outputs 8 }}
{{/with}}

Examples

use term_transcript::{svg::*, Transcript, UserInput};

let mut transcript = Transcript::new();
transcript.add_interaction(
    UserInput::command("test"),
    "Hello, \u{1b}[32mworld\u{1b}[0m!",
);

let template_options = TemplateOptions {
    palette: NamedPalette::Dracula.into(),
    ..TemplateOptions::default()
};
let mut buffer = vec![];
Template::new(template_options).render(&transcript, &mut buffer)?;
let buffer = String::from_utf8(buffer)?;
assert!(buffer.contains(r#"Hello, <span class="fg2">world</span>!"#));

Implementations§

source§

impl Template

source

pub fn new(options: TemplateOptions) -> Self

Initializes the default template based on provided options.

source

pub fn pure_svg(options: TemplateOptions) -> Self

Initializes the pure SVG template based on provided options.

source

pub fn custom(template: HandlebarsTemplate, options: TemplateOptions) -> Self

Initializes a custom template.

source

pub fn render<W: Write>( &self, transcript: &Transcript, destination: W ) -> Result<(), RenderError>

Renders the transcript using the template (usually as an SVG image, although custom templates may use a different output format).

Errors

Returns a Handlebars rendering error, if any. Normally, the only errors could be related to I/O (e.g., the output cannot be written to a file).

Trait Implementations§

source§

impl Debug for Template

source§

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

Formats the value using the given formatter. Read more
source§

impl Default for Template

source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

source§

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

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

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

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

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

source§

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

Mutably borrows from an owned value. Read more
§

impl<T> Downcast for Twhere T: Any,

§

fn into_any(self: Box<T, Global>) -> Box<dyn Any, Global>

Convert Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.
§

fn into_any_rc(self: Rc<T, Global>) -> Rc<dyn Any, Global>

Convert Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
§

fn as_any(&self) -> &(dyn Any + 'static)

Convert &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
§

impl<T> DowncastSync for Twhere T: Any + Send + Sync,

§

fn into_any_arc(self: Arc<T, Global>) -> Arc<dyn Any + Send + Sync, Global>

Convert Arc<Trait> (where Trait: Downcast) to Arc<Any>. Arc<Any> can then be further downcast into Arc<ConcreteType> where ConcreteType implements Trait.
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for Twhere 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, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

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

§

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.
§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more