FilesystemProvider

Struct FilesystemProvider 

Source
pub struct FilesystemProvider { /* private fields */ }
Expand description

A provider reading templates from files on the filesystem.

It can be used in static content generators, when live-reloading a frontend in development or in a scenario where a lot of reading from files is needed to always render the up-to-date version.

Template files are searched following two criterias:

Besides these criterias, you need to note that:

  • The search is (of course) recursive: sub-directories of the allowed paths are also searched
  • Paths are linearly searched, so if you insert the directory “a” containing a file “template.html” then you insert the directory “b” with the same file, the file in the “a” directory will be the first found and used
  • Paths can be directories or files (the file must have one of the allowed extensions)
  • Hidden directories are ignored
  • Symbolic links are followed

To avoid always reading files when they don’t change, a cache is available which will store the parsed files in memory instead of always reading them from the filesystem. By default, it is disabled in debug mode and enabled in release mode, but you can override this preference using either FilesystemProvider::enable_cache or FilesystemProvider::disable_cache. Keep in mind that the files are still read once from the disk, so it is not equivalent to keeping them in the binary. If you can’t afford the small performance overhead or if you don’t want to use an external directory, you should use a StaticMapProvider instead.

Implementations§

Source§

impl FilesystemProvider

Source

pub fn new() -> Self

Create a new empty FilesystemProvider searching HTML files (with .html extension).

Source

pub fn enable_cache(self) -> Self

Force enabling the cache of read files. All files will be read only once, then they will be provided from memory.

In release mode this is enabled by default.

See FilesystemProvider for more information.

Source

pub fn disable_cache(self) -> Self

Force disabling the cache of read files. All files will always be read from the filesystem.

In debug mode this is enabled by default.

See FilesystemProvider for more information.

Source

pub fn with_path<P: AsRef<Path>>(self, path: P) -> Self

Add a path to the list of the paths searched to find templates, using the builder pattern.

It can be a directory or a file having one of the allowed extensions.

Source

pub fn insert_path<P: AsRef<Path>>(&mut self, path: P)

Add a path to the list of the paths searched to find templates.

It can be a directory or a file having one of the allowed extensions.

Source

pub fn remove_path<P: AsRef<Path>>(&mut self, path: P)

Remove a path from the list of the paths searched to find templates.

Source

pub fn with_extension<T: Into<String>>(self, ext: T) -> Self

Add an extension to the list of the allowed file extensions that files must have to be compiled, using the builder pattern.

Source

pub fn insert_extension<T: Into<String>>(&mut self, ext: T)

Add an extension to the list of the allowed file extensions that files must have to be compiled.

Source

pub fn remove_extension<T: Into<String>>(&mut self, ext: T)

Remove an extension from the list of the allowed file extensions that files must have to be compiled.

Source

pub fn get(&self, name: &str) -> Result<ComponentFile<'_, '_>>

Get a template previously inserted into the provider.

§Errors

Returns Error::ComponentNotFound if the template is not found or another Error if the file was not cached and an error happened when parsing it.

§Panics

This function panics if the cache lock is poisoned, which can never happen because insertion or retrieval from a HashMap cannot fail.

Source

pub fn template_names(&self) -> impl Iterator<Item = String> + '_

Returns an iterator over the name of all inserted templates.

Warning: this function is expensive because it needs to read the filesystem each time to find all template files (even if the cache is enabled), use it with caution.

Source

pub fn to_resolver_fn<'a, 'b: 'a>( &'b self, ) -> impl FnMut(&str) -> Result<ComponentFile<'a, 'b>> + 'b

Make a component resolver function from the provider, used in the compile function.

Source

pub fn compile<'a: 'b, 'b>( &self, default_component_name: &str, default_context: &mut Context, ) -> Result<String>

Compile the specified component using the specified context.

Manages the component resolver function under the hood unlike compile.

§Errors

It is up to you to format runtime errors (e.g using error::display_ansi_error or error::display_html_error).

For example, to display the error using ANSI escape codes (to be used in shells) you can call it like this:

use pochoir::{FilesystemProvider, Context};

let provider = FilesystemProvider::new()
    .with_path("templates");

let _compiled = provider.compile("index", &mut Context::new()).map_err(|e| {
    // Runtime error formatting happens here, it uses
    // `pochoir::common::Spanned::component_name` to get
    // the name of the component which raised the error and
    // fetches it from the provider to get the text source of
    // the component
    pochoir::error::display_ansi_error(
        &e,
        &provider.get(
            e.component_name(),
        )
        .expect("component should not be removed from the provider")
        .data,
    )
});
Source

pub fn transform_and_compile<'a: 'b, 'b>( &self, default_component_name: &str, default_context: &mut Context, transformers: &mut Transformers<'_>, ) -> Result<String>

Compile each template while applying transformers.

See transformers and FilesystemProvider::compile.

§Errors

It is up to you to format runtime errors (e.g using error::display_ansi_error or error::display_html_error).

For example, to display the error using ANSI escape codes (to be used in shells) you can call it like this:

use pochoir::{FilesystemProvider, Transformers, Context};

let provider = FilesystemProvider::new()
    .with_path("templates");

let _compiled = provider.transform_and_compile("index", &mut Context::new(), &mut Transformers::new()).map_err(|e| {
    // Runtime error formatting happens here, it uses
    // `pochoir::common::Spanned::component_name` to get
    // the name of the component which raised the error and
    // fetches it from the provider to get the text source of
    // the component
    pochoir::error::display_ansi_error(
        &e,
        &provider.get(
            e.component_name(),
        )
        .expect("component should not be removed from the provider")
        .data,
    )
});

Trait Implementations§

Source§

impl Clone for FilesystemProvider

Source§

fn clone(&self) -> FilesystemProvider

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for FilesystemProvider

Source§

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

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

impl Default for FilesystemProvider

Source§

fn default() -> Self

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

Auto Trait Implementations§

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

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

Source§

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