axum_template/engine/
mod.rs

1//! Types that implement `TemplateEngine` for commonly used template engines
2//!
3//! > Note: each engine is guarded behind a feature with the same name
4//!
5//! # Table of contents
6//!
7//! - [`handlebars`](#handlebars)
8//! - [`minijinja`](#minijinja)
9//! - [`tera`](#tera)
10//!
11//! # `handlebars`
12//!
13//! ```no_run
14#![cfg_attr(feature="handlebars", doc = include_str!("../../examples/handlebars.rs"))]
15//! ```
16//!
17//! # `minijinja`
18//!
19//! ```no_run
20#![cfg_attr(feature="minijinja", doc = include_str!("../../examples/minijinja.rs"))]
21//! ```
22//!
23//! # `tera`
24//!
25//! ```no_run
26#![cfg_attr(feature="tera", doc = include_str!("../../examples/tera.rs"))]
27//! ```
28//!
29
30use axum::{
31    extract::{FromRef, FromRequestParts},
32    http::request::Parts,
33};
34use std::{convert::Infallible, fmt::Debug, sync::Arc};
35
36#[cfg(feature = "handlebars")]
37mod handlebars;
38#[cfg(feature = "handlebars")]
39pub use self::handlebars::*;
40
41#[cfg(feature = "tera")]
42mod tera;
43#[cfg(feature = "tera")]
44pub use self::tera::*;
45
46#[cfg(any(feature = "minijinja", feature = "minijinja-autoreload"))]
47mod minijinja;
48#[cfg(any(feature = "minijinja", feature = "minijinja-autoreload"))]
49pub use self::minijinja::*;
50
51/// A wrapper type that implements [`TemplateEngine`] for multiple
52/// commonly used engines. See [`crate::engine`] for detailed usage instructions
53/// and examples
54///
55/// [`TemplateEngine`]: crate::TemplateEngine
56#[derive(Debug, PartialEq, Eq)]
57pub struct Engine<E> {
58    #[allow(dead_code)]
59    engine: Arc<E>,
60}
61
62impl<E> Engine<E> {
63    /// Creates a new [`Engine`] that wraps the given engine
64    pub fn new(engine: E) -> Self {
65        let engine = Arc::new(engine);
66        Self { engine }
67    }
68}
69
70impl<E> Clone for Engine<E> {
71    fn clone(&self) -> Self {
72        Self {
73            engine: self.engine.clone(),
74        }
75    }
76}
77
78impl<E> From<E> for Engine<E> {
79    fn from(engine: E) -> Self {
80        Self::new(engine)
81    }
82}
83
84impl<ApplicationState, E> FromRequestParts<ApplicationState> for Engine<E>
85where
86    Self: Send + Sync + 'static + FromRef<ApplicationState>,
87    ApplicationState: Send + Sync,
88{
89    type Rejection = Infallible;
90
91    async fn from_request_parts(
92        _: &mut Parts,
93        state: &ApplicationState,
94    ) -> Result<Self, Self::Rejection> {
95        Ok(Self::from_ref(state))
96    }
97}