Skip to main content

Module engine

Module engine 

Source
Expand description

The texl engine: documents, loaders and imports.

An Engine renders templates and loads documents: templates identified by a URI. It owns

  • a base scope with the Swan built-ins and any globals added by the host with Engine::add_builtin;
  • a set of loaders that fetch the source of a document from its URI, one per URI scheme (Engine::add_loader) plus a default loader for paths without a scheme (Engine::add_default_loader);
  • a cache of documents, so that each document is loaded and rendered at most once.

§Documents

Loading a document produces a namespace with four fields:

FieldTypeContent
uriTextThe normalized URI of the document
sourceTextThe template source, as returned by the loader
dataNamespaceThe scope the template was rendered in
renderingTextThe rendered text

The data field holds every name the template assigned, so a document can act as a library of values and functions.

§Imports

Every scope created by the engine has a texl namespace containing texl.import. Templates call texl.import(uri) to load another document. It always returns a promise of the document namespace (or of Nothing, if the document cannot be loaded). Relative URIs resolve against the URI of the importing document, or against the base URL given to Engine::create_scope; in a scope without a document, they resolve against the root path /. The imported document is rendered in a child of the importing scope, so it can read the names of its importer.

§Example

use swan_core::value::Value;
use texl_core::{Engine, loader_fn};

let engine = Engine::new(None);
engine.add_builtin("reader", Value::Text("Ada".into()));
engine.add_default_loader(loader_fn(|uri| async move {
    match uri.as_str() {
        "/greeting.texl" => Ok("Hello <% reader %>!".to_string()),
        _ => Err(format!("{uri}: not found")),
    }
}));

let text = block_on(engine.render(
    r#"<% texl.import("greeting.texl") ~> (doc -> doc.rendering) %>"#
));
assert_eq!(text, "Hello Ada!");

Structs§

Engine
Renders templates and loads documents. See the module documentation.

Functions§

loader_fn
Builds a LoaderFn from a closure that takes the URI and returns a future.

Type Aliases§

LoaderFn
A host-provided function that fetches the source of a document.