├── .github ├── dependabot.yml └── workflows │ ├── release.yml │ └── test.yml ├── .gitignore ├── Cargo.toml ├── LICENSE ├── Makefile ├── README.md ├── examples ├── custom_engine.rs ├── custom_key.rs ├── dynamic_template.rs ├── handlebars.rs ├── minijinja-autoreload.rs ├── minijinja.rs ├── nested.rs ├── templates │ ├── minijinja │ │ └── hello.html │ └── tera │ │ └── {name}.html └── tera.rs ├── src ├── engine │ ├── handlebars.rs │ ├── minijinja.rs │ ├── mod.rs │ └── tera.rs ├── key.rs ├── lib.rs ├── render.rs └── traits.rs └── tests ├── engine.rs ├── error.rs ├── key.rs └── render.rs /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 5 | 6 | version: 2 7 | updates: 8 | - package-ecosystem: "cargo" # See documentation for possible values 9 | directory: "/" # Location of package manifests 10 | schedule: 11 | interval: "daily" 12 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release new version 2 | on: 3 | push: 4 | tags: 5 | - "*" 6 | workflow_dispatch: 7 | env: 8 | CARGO_TERM_COLOR: always 9 | jobs: 10 | publish_crate: 11 | runs-on: ubuntu-latest 12 | strategy: 13 | matrix: 14 | toolchain: 15 | - stable 16 | steps: 17 | - uses: actions/checkout@v3 18 | - uses: actions/cache@v3 19 | with: 20 | path: | 21 | ~/.cargo/bin/ 22 | ~/.cargo/registry/index/ 23 | ~/.cargo/registry/cache/ 24 | ~/.cargo/git/db/ 25 | # target/ 26 | key: ${{ runner.os }}-cargo-${{ matrix.toolchain }} # -${{ hashFiles('**/Cargo.lock') }} 27 | - run: 28 | rustup update ${{ matrix.toolchain }} && rustup default ${{ 29 | matrix.toolchain }} 30 | - run: cargo publish 31 | env: 32 | CARGO_REGISTRY_TOKEN: ${{ secrets.CRATESIO_REGISTRY_TOKEN }} 33 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Check changes 2 | on: 3 | push: 4 | branches: 5 | - "**" 6 | - "*" 7 | pull_request: 8 | branches: 9 | - "master" 10 | - "main" 11 | env: 12 | CARGO_TERM_COLOR: always 13 | jobs: 14 | make_ci: 15 | runs-on: ubuntu-latest 16 | strategy: 17 | matrix: 18 | toolchain: 19 | - stable 20 | - "1.83" 21 | # - beta 22 | # - nightly 23 | steps: 24 | - uses: actions/checkout@v3 25 | - uses: actions/cache@v3 26 | with: 27 | path: | 28 | ~/.cargo/bin/ 29 | ~/.cargo/registry/index/ 30 | ~/.cargo/registry/cache/ 31 | ~/.cargo/git/db/ 32 | # target/ 33 | key: ${{ runner.os }}-cargo-${{ matrix.toolchain }} # ${{ hashFiles('**/Cargo.lock') }} 34 | - run: 35 | rustup update ${{ matrix.toolchain }} && rustup default ${{ 36 | matrix.toolchain }} && rustup component add clippy rustfmt 37 | - run: make ci 38 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | /target/ 4 | 5 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 6 | # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html 7 | Cargo.lock 8 | 9 | # These are backup files generated by rustfmt 10 | **/*.rs.bk 11 | 12 | # Added by cargo 13 | 14 | /target 15 | /Cargo.lock 16 | 17 | # Editors 18 | .idea 19 | *.iml 20 | .vscode 21 | .zed 22 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "axum-template" 3 | version = "3.0.0" 4 | edition = "2021" 5 | license = "MIT" 6 | description = "Layers, extractors and template engine wrappers for axum based Web MVC applications" 7 | homepage = "https://github.com/Altair-Bueno/axum-template" 8 | repository = "https://github.com/Altair-Bueno/axum-template" 9 | readme = "README.md" 10 | keywords = ["axum", "minijinja", "tera", "handlebars", "mvc"] 11 | categories = ["template-engine", "web-programming"] 12 | rust-version = "1.83.0" 13 | 14 | [package.metadata.docs.rs] 15 | all-features = true 16 | 17 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 18 | 19 | [dependencies] 20 | serde = "1" 21 | thiserror = "2" 22 | 23 | # Supported template engines 24 | tera = { version = "1.19.0", optional = true, default-features = false } 25 | handlebars = { version = "6.0.0", optional = true, default-features = false } 26 | minijinja = { version = "2.0.1", optional = true, default-features = false } 27 | minijinja-autoreload = { version = "2.0.1", optional = true, default-features = false } 28 | 29 | [dependencies.axum] 30 | version = "0.8.0" 31 | default-features = false 32 | features = ["matched-path"] 33 | 34 | [dev-dependencies] 35 | tokio = { version = "1.22.0", features = ["full"] } 36 | serde = { version = "1", features = ["derive"] } 37 | tower-http = { version = "0.6.0", features = ["full"] } 38 | tower = { version = "0.5.0", features = ["full"] } 39 | axum = { version = "0.8.0", features = ["macros", "tokio"] } 40 | rstest = "0.25.0" 41 | speculoos = "0.13.0" 42 | anyhow = "1.0.61" 43 | hyper = "1.0.1" 44 | rand = "0.9.0" 45 | 46 | [[example]] 47 | name = "tera" 48 | required-features = ["tera"] 49 | 50 | [[example]] 51 | name = "handlebars" 52 | required-features = ["handlebars"] 53 | 54 | [[example]] 55 | name = "minijinja" 56 | required-features = ["minijinja"] 57 | 58 | [[example]] 59 | name = "minijinja-autoreload" 60 | required-features = ["minijinja-autoreload", "minijinja-autoreload/watch-fs", "minijinja", "minijinja/loader"] 61 | 62 | [[example]] 63 | name = "custom_key" 64 | required-features = ["tera"] 65 | 66 | [[example]] 67 | name = "custom_engine" 68 | 69 | [[example]] 70 | name = "nested" 71 | required-features = ["handlebars"] 72 | 73 | [[example]] 74 | name = "dynamic_template" 75 | required-features = ["handlebars"] 76 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Altair Bueno 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | CARGO = cargo 2 | CARGO_CCARGS = 3 | CARGO_EXAMPLES = custom_engine \ 4 | custom_key \ 5 | handlebars \ 6 | minijinja \ 7 | nested \ 8 | tera 9 | 10 | ################################################################################ 11 | # Main goals 12 | ci: CARGO_CCARGS = --all-features --verbose 13 | ci: test build lint 14 | 15 | test: 16 | $(CARGO) test $(CARGO_CCARGS) 17 | 18 | lint: lint/clippy lint/fmt 19 | 20 | fmt: 21 | $(CARGO) fmt 22 | 23 | build: build/example build/crate 24 | ################################################################################ 25 | build/example: $(addprefix build/example/, $(CARGO_EXAMPLES)) 26 | 27 | build/example/%: 28 | $(CARGO) build --example=$* $(CARGO_CCARGS) 29 | 30 | build/crate: 31 | $(CARGO) build $(CARGO_CCARGS) 32 | 33 | lint/clippy: 34 | $(CARGO) clippy $(CARGO_CCARGS) 35 | 36 | lint/fmt: 37 | $(CARGO) fmt --check 38 | 39 | ################################################################################ 40 | 41 | .PHONY: test ci \ 42 | $(filter build%, $(MAKECMDGOALS)) \ 43 | $(filter lint%, $(MAKECMDGOALS)) 44 | 45 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # axum-template 2 | 3 | [![LICENSE](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE) 4 | [![Test status](https://github.com/Altair-Bueno/axum-template/actions/workflows/test.yml/badge.svg)](https://github.com/Altair-Bueno/axum-template/actions/workflows/test.yml) 5 | [![Crates.io Version](https://img.shields.io/crates/v/axum-template.svg)](https://crates.io/crates/axum-template) 6 | [![docs.rs](https://img.shields.io/docsrs/axum-template)](https://docs.rs/axum-template) 7 | ![MSRV](https://img.shields.io/crates/msrv/axum-template) 8 | 9 | Layers, extractors and template engine wrappers for [axum] based Web MVC 10 | applications 11 | 12 | # Getting started 13 | 14 | The [`engine`] module contains detailed usage examples for each of the supported 15 | template engines. 16 | 17 | If you plan using an unsupported engine, check the [`TemplateEngine`] docs 18 | 19 | # Available features 20 | 21 | - `handlebars`: Enables [handlebars] support 22 | - `minijinja`: Enables [minijinja] support 23 | - `minijinja-autoreload`: Enables [minijinja-autoreload] support 24 | - `tera`: Enables [tera] support 25 | 26 | # Useful links 27 | 28 | - [Documentation] 29 | - [Examples] 30 | - [Source code] 31 | 32 | ## Learning resources 33 | 34 | Tutorials, blog posts and success stories not affiliated to this project. They 35 | might be useful for new commers of the Rust programming language or experienced 36 | devs that would like to see this library in action. 37 | 38 | - [Server-side rendering in Rust - a Dall.E use-case](https://blog.frankel.ch/server-side-rendering-rust/) 39 | 40 | # License 41 | 42 | Licensed under the MIT license. See [LICENSE] for more information 43 | 44 | [`engine`]: crate::engine 45 | [`TemplateEngine`]: crate::TemplateEngine 46 | [LICENSE]: https://github.com/Altair-Bueno/axum-template/blob/main/LICENSE 47 | [Documentation]: https://docs.rs/axum-template 48 | [Examples]: https://github.com/Altair-Bueno/axum-template/tree/main/examples 49 | [Source code]: https://github.com/Altair-Bueno/axum-template 50 | [axum]: https://github.com/tokio-rs/axum 51 | [handlebars]: https://crates.io/crates/handlebars 52 | [minijinja]: https://crates.io/crates/minijinja 53 | [minijinja-autoreload]: https://crates.io/crates/minijinja-autoreload 54 | [tera]: https://crates.io/crates/tera 55 | -------------------------------------------------------------------------------- /examples/custom_engine.rs: -------------------------------------------------------------------------------- 1 | //! Creating your own custom engines 2 | //! 3 | //! Run the example using 4 | //! 5 | //! ```sh 6 | //! cargo run --example=custom_engine 7 | //! ``` 8 | 9 | use std::{convert::Infallible, net::Ipv4Addr}; 10 | 11 | use axum::{ 12 | extract::{FromRef, FromRequestParts}, 13 | http::request::Parts, 14 | response::IntoResponse, 15 | routing::get, 16 | serve, Router, 17 | }; 18 | use axum_template::{Key, RenderHtml, TemplateEngine}; 19 | use serde::Serialize; 20 | use tokio::net::TcpListener; 21 | 22 | // Clone is required by `axum::extract::Extension` 23 | #[derive(Debug, Clone)] 24 | pub struct CustomEngine; 25 | 26 | impl TemplateEngine for CustomEngine { 27 | // See `std::convert::Infallible` 28 | type Error = Infallible; 29 | 30 | fn render(&self, key: &str, _: S) -> Result { 31 | // This engine just returns the key 32 | Ok(key.to_owned()) 33 | } 34 | } 35 | 36 | impl FromRequestParts for CustomEngine 37 | where 38 | Self: Send + Sync + 'static + FromRef, 39 | ApplicationState: Send + Sync, 40 | { 41 | type Rejection = Infallible; 42 | 43 | async fn from_request_parts( 44 | _: &mut Parts, 45 | state: &ApplicationState, 46 | ) -> Result { 47 | Ok(Self::from_ref(state)) 48 | } 49 | } 50 | 51 | async fn get_name( 52 | // Obtain the engine 53 | engine: AppEngine, 54 | // Extract the key 55 | Key(key): Key, 56 | ) -> impl IntoResponse { 57 | RenderHtml(key, engine, ()) 58 | } 59 | 60 | type AppEngine = CustomEngine; 61 | 62 | #[derive(Clone, FromRef)] 63 | struct AppState { 64 | engine: AppEngine, 65 | } 66 | 67 | #[tokio::main] 68 | async fn main() { 69 | let engine = CustomEngine; 70 | let app = Router::new() 71 | .route("/{name}", get(get_name)) 72 | // Share the engine using `axum::Extension`, or implement `tower::Layer` 73 | // manually for your engine 74 | .with_state(AppState { engine }); 75 | 76 | println!("See example: http://127.0.0.1:8080/example"); 77 | let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 8080)) 78 | .await 79 | .unwrap(); 80 | serve(listener, app.into_make_service()).await.unwrap(); 81 | } 82 | -------------------------------------------------------------------------------- /examples/custom_key.rs: -------------------------------------------------------------------------------- 1 | //! Applying transformations to keys (prefixes and suffixes, for example) 2 | //! 3 | //! Run the example using 4 | //! 5 | //! ```sh 6 | //! cargo run --example=custom_key --features=tera 7 | //! ``` 8 | 9 | use std::net::Ipv4Addr; 10 | 11 | use axum::{ 12 | extract::{rejection::MatchedPathRejection, FromRef, FromRequestParts, MatchedPath, Path}, 13 | http::request::Parts, 14 | response::IntoResponse, 15 | routing::get, 16 | serve, RequestPartsExt, Router, 17 | }; 18 | use axum_template::{engine::Engine, RenderHtml}; 19 | use serde::Serialize; 20 | use tera::Tera; 21 | use tokio::net::TcpListener; 22 | 23 | // Because Tera::new loads an entire folder, we need to remove the `/` prefix 24 | // and add a `.html` suffix. We can implement our own custom key extractor that 25 | // transform the key 26 | pub struct CustomKey(pub String); 27 | 28 | impl FromRequestParts for CustomKey 29 | where 30 | S: Send + Sync, 31 | { 32 | type Rejection = MatchedPathRejection; 33 | 34 | async fn from_request_parts(parts: &mut Parts, _: &S) -> Result { 35 | let key = parts 36 | // `axum_template::Key` internally uses `axum::extract::MatchedPath` 37 | .extract::() 38 | .await? 39 | .as_str() 40 | .chars() 41 | // Remove the first character `/` 42 | .skip(1) 43 | // Add the `.html` suffix 44 | .chain(".html".chars()) 45 | .collect(); 46 | Ok(CustomKey(key)) 47 | } 48 | } 49 | 50 | // Type alias for our engine. For this example, we are using Tera 51 | type AppEngine = Engine; 52 | 53 | #[derive(Debug, Serialize)] 54 | pub struct Person { 55 | name: String, 56 | } 57 | 58 | async fn get_name( 59 | // Obtain the engine 60 | engine: AppEngine, 61 | // Extract the custom key 62 | CustomKey(template): CustomKey, 63 | Path(name): Path, 64 | ) -> impl IntoResponse { 65 | let person = Person { name }; 66 | 67 | RenderHtml(template, engine, person) 68 | } 69 | 70 | #[derive(Clone, FromRef)] 71 | struct AppState { 72 | engine: AppEngine, 73 | } 74 | 75 | #[tokio::main] 76 | async fn main() { 77 | // Tera allows loading an entire folder using glob patterns. This will load 78 | // our file examples/templates/tera/{name}.html with the key {name}.html 79 | let tera = Tera::new("examples/templates/tera/**/*.html").expect("Template folder not found"); 80 | let app = Router::new() 81 | .route("/{name}", get(get_name)) 82 | .with_state(AppState { 83 | engine: Engine::from(tera), 84 | }); 85 | 86 | println!("See example: http://127.0.0.1:8080/example"); 87 | let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 8080)) 88 | .await 89 | .unwrap(); 90 | serve(listener, app.into_make_service()).await.unwrap(); 91 | } 92 | -------------------------------------------------------------------------------- /examples/dynamic_template.rs: -------------------------------------------------------------------------------- 1 | //! Simple usage of using `axum_template` with the `handlebars` crate 2 | //! 3 | //! Run the example using 4 | //! 5 | //! ```sh 6 | //! cargo run --example=dynamic_template --features=handlebars 7 | //! ``` 8 | use std::net::Ipv4Addr; 9 | 10 | use axum::{extract::FromRef, response::IntoResponse, routing::get, serve, Router}; 11 | use axum_template::{engine::Engine, RenderHtml}; 12 | use handlebars::Handlebars; 13 | use tokio::net::TcpListener; 14 | 15 | // Type alias for our engine. For this example, we are using Handlebars 16 | type AppEngine = Engine>; 17 | 18 | async fn get_luck( 19 | // Obtain the engine 20 | engine: AppEngine, 21 | ) -> impl IntoResponse { 22 | // Anything that can be coerced to &str can be used as Key. 23 | let key = if rand::random::() % 6 == 0 { 24 | "lucky" 25 | } else { 26 | "unlucky" 27 | }; 28 | RenderHtml(key, engine, &()) 29 | } 30 | 31 | // Define your application shared state 32 | #[derive(Clone, FromRef)] 33 | struct AppState { 34 | engine: AppEngine, 35 | } 36 | 37 | #[tokio::main] 38 | async fn main() { 39 | // Set up the Handlebars engine with the same route paths as the Axum router 40 | let mut hbs = Handlebars::new(); 41 | hbs.register_template_string("lucky", "

Winner winner chicken dinner

") 42 | .unwrap(); 43 | hbs.register_template_string("unlucky", "

Try again!

") 44 | .unwrap(); 45 | 46 | let app = Router::new() 47 | .route("/example", get(get_luck)) 48 | // Create the application state 49 | .with_state(AppState { 50 | engine: Engine::from(hbs), 51 | }); 52 | println!("See example: http://127.0.0.1:8080/example"); 53 | 54 | let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 8080)) 55 | .await 56 | .unwrap(); 57 | serve(listener, app.into_make_service()).await.unwrap(); 58 | } 59 | -------------------------------------------------------------------------------- /examples/handlebars.rs: -------------------------------------------------------------------------------- 1 | //! Simple usage of using `axum_template` with the `handlebars` crate 2 | //! 3 | //! Run the example using 4 | //! 5 | //! ```sh 6 | //! cargo run --example=handlebars --features=handlebars 7 | //! ``` 8 | use std::net::Ipv4Addr; 9 | 10 | use axum::{ 11 | extract::{FromRef, Path}, 12 | response::IntoResponse, 13 | routing::get, 14 | serve, Router, 15 | }; 16 | use axum_template::{engine::Engine, Key, RenderHtml}; 17 | use handlebars::Handlebars; 18 | use serde::Serialize; 19 | use tokio::net::TcpListener; 20 | 21 | // Type alias for our engine. For this example, we are using Handlebars 22 | type AppEngine = Engine>; 23 | 24 | #[derive(Debug, Serialize)] 25 | pub struct Person { 26 | name: String, 27 | } 28 | 29 | async fn get_name( 30 | // Obtain the engine 31 | engine: AppEngine, 32 | // Extract the key 33 | Key(key): Key, 34 | Path(name): Path, 35 | ) -> impl IntoResponse { 36 | let person = Person { name }; 37 | 38 | RenderHtml(key, engine, person) 39 | } 40 | 41 | // Define your application shared state 42 | #[derive(Clone, FromRef)] 43 | struct AppState { 44 | engine: AppEngine, 45 | } 46 | 47 | #[tokio::main] 48 | async fn main() { 49 | // Set up the Handlebars engine with the same route paths as the Axum router 50 | let mut hbs = Handlebars::new(); 51 | hbs.register_template_string("/{name}", "

Hello HandleBars!

{{name}}

") 52 | .unwrap(); 53 | 54 | let app = Router::new() 55 | .route("/{name}", get(get_name)) 56 | // Create the application state 57 | .with_state(AppState { 58 | engine: Engine::from(hbs), 59 | }); 60 | println!("See example: http://127.0.0.1:8080/example"); 61 | 62 | let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 8080)) 63 | .await 64 | .unwrap(); 65 | serve(listener, app.into_make_service()).await.unwrap(); 66 | } 67 | -------------------------------------------------------------------------------- /examples/minijinja-autoreload.rs: -------------------------------------------------------------------------------- 1 | //! Simple usage of using `axum_template` with the `minijinja-autoreload` crate 2 | //! 3 | //! Run the example using 4 | //! 5 | //! ```sh 6 | //! cargo run --example=minijinja-autoreload --features=minijinja,minijinja/loader,minijinja-autoreload,minijinja-autoreload/watch-fs 7 | //! ``` 8 | use axum::{ 9 | extract::{FromRef, Path}, 10 | response::IntoResponse, 11 | routing::get, 12 | serve, Router, 13 | }; 14 | use axum_template::{engine::Engine, RenderHtml}; 15 | use minijinja::{path_loader, Environment}; 16 | use minijinja_autoreload::AutoReloader; 17 | use serde::Serialize; 18 | use std::net::Ipv4Addr; 19 | use std::path::PathBuf; 20 | use tokio::net::TcpListener; 21 | 22 | // Type alias for our engine. For this example, we are using Mini Jinja 23 | type AppEngine = Engine; 24 | 25 | #[derive(Debug, Serialize)] 26 | pub struct Person { 27 | name: String, 28 | } 29 | 30 | async fn get_name(engine: AppEngine, Path(name): Path) -> impl IntoResponse { 31 | let person = Person { name }; 32 | 33 | RenderHtml("hello.html", engine, person) 34 | } 35 | 36 | // Define your application shared state 37 | #[derive(Clone, FromRef)] 38 | struct AppState { 39 | engine: AppEngine, 40 | } 41 | 42 | #[tokio::main] 43 | async fn main() { 44 | // Set up the `minijinja` engine with the same route paths as the Axum router 45 | let jinja = AutoReloader::new(move |notifier| { 46 | let template_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) 47 | .join("examples") 48 | .join("templates") 49 | .join("minijinja"); 50 | let mut env = Environment::new(); 51 | env.set_loader(path_loader(&template_path)); 52 | notifier.set_fast_reload(true); 53 | notifier.watch_path(&template_path, true); 54 | Ok(env) 55 | }); 56 | 57 | let app = Router::new() 58 | .route("/{name}", get(get_name)) 59 | // Create the application state 60 | .with_state(AppState { 61 | engine: Engine::from(jinja), 62 | }); 63 | 64 | println!("See example: http://127.0.0.1:8080/example"); 65 | 66 | let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 8080)) 67 | .await 68 | .unwrap(); 69 | serve(listener, app.into_make_service()).await.unwrap(); 70 | } 71 | -------------------------------------------------------------------------------- /examples/minijinja.rs: -------------------------------------------------------------------------------- 1 | //! Simple usage of using `axum_template` with the `minijinja` crate 2 | //! 3 | //! Run the example using 4 | //! 5 | //! ```sh 6 | //! cargo run --example=minijinja --features=minijinja 7 | //! ``` 8 | use std::net::Ipv4Addr; 9 | 10 | use axum::{ 11 | extract::{FromRef, Path}, 12 | response::IntoResponse, 13 | routing::get, 14 | serve, Router, 15 | }; 16 | use axum_template::{engine::Engine, Key, RenderHtml}; 17 | use minijinja::Environment; 18 | use serde::Serialize; 19 | use tokio::net::TcpListener; 20 | 21 | // Type alias for our engine. For this example, we are using Mini Jinja 22 | type AppEngine = Engine>; 23 | 24 | #[derive(Debug, Serialize)] 25 | pub struct Person { 26 | name: String, 27 | } 28 | 29 | async fn get_name( 30 | // Obtain the engine 31 | engine: AppEngine, 32 | // Extract the key 33 | Key(key): Key, 34 | Path(name): Path, 35 | ) -> impl IntoResponse { 36 | let person = Person { name }; 37 | 38 | RenderHtml(key, engine, person) 39 | } 40 | 41 | // Define your application shared state 42 | #[derive(Clone, FromRef)] 43 | struct AppState { 44 | engine: AppEngine, 45 | } 46 | 47 | #[tokio::main] 48 | async fn main() { 49 | // Set up the `minijinja` engine with the same route paths as the Axum router 50 | let mut jinja = Environment::new(); 51 | jinja 52 | .add_template("/{name}", "

Hello Minijinja!

{{name}}

") 53 | .unwrap(); 54 | 55 | let app = Router::new() 56 | .route("/{name}", get(get_name)) 57 | // Create the application state 58 | .with_state(AppState { 59 | engine: Engine::from(jinja), 60 | }); 61 | 62 | println!("See example: http://127.0.0.1:8080/example"); 63 | 64 | let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 8080)) 65 | .await 66 | .unwrap(); 67 | serve(listener, app.into_make_service()).await.unwrap(); 68 | } 69 | -------------------------------------------------------------------------------- /examples/nested.rs: -------------------------------------------------------------------------------- 1 | //! Showcases nested routers and the `Key` extractor 2 | //! 3 | //! Run the example using 4 | //! 5 | //! ```sh 6 | //! cargo run --example=nested --features=handlebars 7 | //! ``` 8 | 9 | use std::net::Ipv4Addr; 10 | 11 | use axum::{ 12 | extract::{FromRef, Path}, 13 | response::IntoResponse, 14 | routing::get, 15 | serve, Router, 16 | }; 17 | use axum_template::{engine::Engine, Key, RenderHtml}; 18 | use handlebars::Handlebars; 19 | use serde::Serialize; 20 | use tokio::net::TcpListener; 21 | 22 | type AppEngine = Engine>; 23 | 24 | #[derive(Debug, Serialize)] 25 | pub struct Person { 26 | name: String, 27 | } 28 | 29 | async fn get_name(engine: AppEngine, Key(key): Key, Path(name): Path) -> impl IntoResponse { 30 | let person = Person { name }; 31 | 32 | RenderHtml(key, engine, person) 33 | } 34 | 35 | #[derive(Clone, FromRef)] 36 | struct AppState { 37 | engine: AppEngine, 38 | } 39 | 40 | #[tokio::main] 41 | async fn main() { 42 | let mut hbs = Handlebars::new(); 43 | hbs.register_template_string("/{name}", "Simple {{ name }}") 44 | .unwrap(); 45 | hbs.register_template_string("/nested/{name}", "Nested {{name}}") 46 | .unwrap(); 47 | 48 | let nested = Router::new().route("/{name}", get(get_name)); 49 | 50 | let app = Router::new() 51 | .route("/{name}", get(get_name)) 52 | .nest("/nested", nested) 53 | .with_state(AppState { 54 | engine: Engine::from(hbs), 55 | }); 56 | 57 | println!("See example: http://127.0.0.1:8080/example"); 58 | let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 8080)) 59 | .await 60 | .unwrap(); 61 | serve(listener, app.into_make_service()).await.unwrap(); 62 | } 63 | -------------------------------------------------------------------------------- /examples/templates/minijinja/hello.html: -------------------------------------------------------------------------------- 1 |

Hello Minijinja!

{{name}}

-------------------------------------------------------------------------------- /examples/templates/tera/{name}.html: -------------------------------------------------------------------------------- 1 |

Hello Folder!

2 |

{{name}}

-------------------------------------------------------------------------------- /examples/tera.rs: -------------------------------------------------------------------------------- 1 | //! Simple usage of using `axum_template` with the `tera` crate 2 | //! 3 | //! Run the example using 4 | //! 5 | //! ```sh 6 | //! cargo run --example=tera --features=tera 7 | //! ``` 8 | use std::net::Ipv4Addr; 9 | 10 | use axum::{ 11 | extract::{FromRef, Path}, 12 | response::IntoResponse, 13 | routing::get, 14 | serve, Router, 15 | }; 16 | use axum_template::{engine::Engine, Key, RenderHtml}; 17 | use serde::Serialize; 18 | use tera::Tera; 19 | use tokio::net::TcpListener; 20 | 21 | // Type alias for our engine. For this example, we are using Tera 22 | type AppEngine = Engine; 23 | 24 | #[derive(Debug, Serialize)] 25 | pub struct Person { 26 | name: String, 27 | } 28 | 29 | async fn get_name( 30 | // Obtain the engine 31 | engine: AppEngine, 32 | // Extract the key 33 | Key(key): Key, 34 | Path(name): Path, 35 | ) -> impl IntoResponse { 36 | let person = Person { name }; 37 | 38 | RenderHtml(key, engine, person) 39 | } 40 | 41 | // Define your application shared state 42 | #[derive(Clone, FromRef)] 43 | struct AppState { 44 | engine: AppEngine, 45 | } 46 | 47 | #[tokio::main] 48 | async fn main() { 49 | // Set up the Tera engine with the same route paths as the Axum router 50 | let mut tera = Tera::default(); 51 | tera.add_raw_template("/{name}", "

Hello Tera!

{{name}}

") 52 | .unwrap(); 53 | 54 | let app = Router::new() 55 | .route("/{name}", get(get_name)) 56 | // Create the application state 57 | .with_state(AppState { 58 | engine: Engine::from(tera), 59 | }); 60 | 61 | println!("See example: http://127.0.0.1:8080/example"); 62 | let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 8080)) 63 | .await 64 | .unwrap(); 65 | serve(listener, app.into_make_service()).await.unwrap(); 66 | } 67 | -------------------------------------------------------------------------------- /src/engine/handlebars.rs: -------------------------------------------------------------------------------- 1 | use crate::TemplateEngine; 2 | 3 | use super::Engine; 4 | 5 | use axum::{http::StatusCode, response::IntoResponse}; 6 | use handlebars::Handlebars; 7 | use thiserror::Error; 8 | 9 | impl TemplateEngine for Engine> { 10 | type Error = HandlebarsError; 11 | 12 | fn render(&self, key: &str, data: D) -> Result { 13 | let rendered = self.engine.render(key, &data)?; 14 | 15 | Ok(rendered) 16 | } 17 | } 18 | 19 | /// Error wrapper for [`handlebars::RenderError`] 20 | #[derive(Error, Debug)] 21 | pub enum HandlebarsError { 22 | /// See [`handlebars::RenderError`] 23 | #[error(transparent)] 24 | RenderError(#[from] handlebars::RenderError), 25 | } 26 | 27 | impl IntoResponse for HandlebarsError { 28 | fn into_response(self) -> axum::response::Response { 29 | (StatusCode::INTERNAL_SERVER_ERROR, self.to_string()).into_response() 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/engine/minijinja.rs: -------------------------------------------------------------------------------- 1 | use crate::TemplateEngine; 2 | 3 | use super::Engine; 4 | 5 | use axum::{http::StatusCode, response::IntoResponse}; 6 | 7 | #[cfg(feature = "minijinja")] 8 | use minijinja::Environment; 9 | 10 | #[cfg(feature = "minijinja-autoreload")] 11 | use minijinja_autoreload::AutoReloader; 12 | 13 | use thiserror::Error; 14 | 15 | #[cfg(feature = "minijinja")] 16 | impl TemplateEngine for Engine> { 17 | type Error = MinijinjaError; 18 | 19 | fn render(&self, key: &str, data: D) -> Result { 20 | let template = self.engine.get_template(key)?; 21 | let rendered = template.render(&data)?; 22 | 23 | Ok(rendered) 24 | } 25 | } 26 | 27 | #[cfg(feature = "minijinja-autoreload")] 28 | impl TemplateEngine for Engine { 29 | type Error = MinijinjaError; 30 | 31 | fn render(&self, key: &str, data: D) -> Result { 32 | let reloader = self.engine.acquire_env()?; 33 | let template = reloader.get_template(key)?; 34 | // let template = self.engine.get_template(key)?; 35 | let rendered = template.render(&data)?; 36 | 37 | Ok(rendered) 38 | } 39 | } 40 | 41 | /// Error wrapper for [`minijinja::Error`] 42 | #[derive(Error, Debug)] 43 | pub enum MinijinjaError { 44 | /// See [`minijinja::Error`] 45 | #[error(transparent)] 46 | RenderError(#[from] minijinja::Error), 47 | } 48 | 49 | impl IntoResponse for MinijinjaError { 50 | fn into_response(self) -> axum::response::Response { 51 | (StatusCode::INTERNAL_SERVER_ERROR, self.to_string()).into_response() 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/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 | 30 | use axum::{ 31 | extract::{FromRef, FromRequestParts}, 32 | http::request::Parts, 33 | }; 34 | use std::{convert::Infallible, fmt::Debug, sync::Arc}; 35 | 36 | #[cfg(feature = "handlebars")] 37 | mod handlebars; 38 | #[cfg(feature = "handlebars")] 39 | pub use self::handlebars::*; 40 | 41 | #[cfg(feature = "tera")] 42 | mod tera; 43 | #[cfg(feature = "tera")] 44 | pub use self::tera::*; 45 | 46 | #[cfg(any(feature = "minijinja", feature = "minijinja-autoreload"))] 47 | mod minijinja; 48 | #[cfg(any(feature = "minijinja", feature = "minijinja-autoreload"))] 49 | pub 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)] 57 | pub struct Engine { 58 | #[allow(dead_code)] 59 | engine: Arc, 60 | } 61 | 62 | impl Engine { 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 | 70 | impl Clone for Engine { 71 | fn clone(&self) -> Self { 72 | Self { 73 | engine: self.engine.clone(), 74 | } 75 | } 76 | } 77 | 78 | impl From for Engine { 79 | fn from(engine: E) -> Self { 80 | Self::new(engine) 81 | } 82 | } 83 | 84 | impl FromRequestParts for Engine 85 | where 86 | Self: Send + Sync + 'static + FromRef, 87 | ApplicationState: Send + Sync, 88 | { 89 | type Rejection = Infallible; 90 | 91 | async fn from_request_parts( 92 | _: &mut Parts, 93 | state: &ApplicationState, 94 | ) -> Result { 95 | Ok(Self::from_ref(state)) 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /src/engine/tera.rs: -------------------------------------------------------------------------------- 1 | use crate::TemplateEngine; 2 | 3 | use super::Engine; 4 | 5 | use axum::{http::StatusCode, response::IntoResponse}; 6 | use tera::{Context, Tera}; 7 | use thiserror::Error; 8 | 9 | impl TemplateEngine for Engine { 10 | type Error = TeraError; 11 | 12 | fn render(&self, key: &str, data: D) -> Result { 13 | let data = Context::from_serialize(data)?; 14 | let rendered = self.engine.render(key, &data)?; 15 | 16 | Ok(rendered) 17 | } 18 | } 19 | 20 | /// Error wrapper for [`tera::Error`] 21 | #[derive(Error, Debug)] 22 | pub enum TeraError { 23 | /// See [`tera::Error`] 24 | #[error(transparent)] 25 | RenderError(#[from] tera::Error), 26 | } 27 | 28 | impl IntoResponse for TeraError { 29 | fn into_response(self) -> axum::response::Response { 30 | (StatusCode::INTERNAL_SERVER_ERROR, self.to_string()).into_response() 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/key.rs: -------------------------------------------------------------------------------- 1 | use axum::{ 2 | extract::{ 3 | rejection::MatchedPathRejection, FromRequestParts, MatchedPath, OptionalFromRequestParts, 4 | }, 5 | http::request::Parts, 6 | RequestPartsExt, 7 | }; 8 | 9 | /// Extracts matched path of the request 10 | /// 11 | /// # Usage 12 | /// 13 | /// ``` 14 | /// # use axum::{response::IntoResponse, Router, routing::get}; 15 | /// # use axum_template::Key; 16 | /// async fn handler( 17 | /// Key(key): Key 18 | /// ) -> impl IntoResponse 19 | /// { 20 | /// key 21 | /// } 22 | /// 23 | /// let router: Router<()> = Router::new() 24 | /// // key == "/some/route" 25 | /// .route("/some/route", get(handler)) 26 | /// // key == "/{dynamic}" 27 | /// .route("/{dynamic}", get(handler)); 28 | /// ``` 29 | /// 30 | /// # Additional resources 31 | /// 32 | /// - [`MatchedPath`] 33 | /// - Example: [`custom_key.rs`] 34 | /// 35 | /// [`MatchedPath`]: axum::extract::MatchedPath 36 | /// [`custom_key.rs`]: https://github.com/Altair-Bueno/axum-template/blob/main/examples/custom_key.rs 37 | #[derive(Debug, Clone, PartialEq, Eq)] 38 | pub struct Key(pub String); 39 | 40 | impl FromRequestParts for Key 41 | where 42 | S: Send + Sync, 43 | { 44 | type Rejection = MatchedPathRejection; 45 | 46 | async fn from_request_parts(parts: &mut Parts, _: &S) -> Result { 47 | let path = parts.extract::().await?.as_str().to_owned(); 48 | Ok(Key(path)) 49 | } 50 | } 51 | 52 | impl OptionalFromRequestParts for Key 53 | where 54 | S: Send + Sync, 55 | { 56 | type Rejection = >::Rejection; 57 | 58 | async fn from_request_parts( 59 | parts: &mut Parts, 60 | state: &S, 61 | ) -> Result, Self::Rejection> { 62 | let path = 63 | >::from_request_parts(parts, state).await?; 64 | Ok(path.map(|path| Key(path.as_str().to_owned()))) 65 | } 66 | } 67 | 68 | impl AsRef for Key { 69 | fn as_ref(&self) -> &str { 70 | self.0.as_str() 71 | } 72 | } 73 | 74 | impl From for Key { 75 | fn from(s: String) -> Self { 76 | Self(s) 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![doc = include_str!("../README.md")] 2 | #![warn( 3 | clippy::all, 4 | clippy::dbg_macro, 5 | clippy::todo, 6 | clippy::empty_enum, 7 | clippy::enum_glob_use, 8 | clippy::mem_forget, 9 | clippy::unused_self, 10 | clippy::filter_map_next, 11 | clippy::needless_continue, 12 | clippy::needless_borrow, 13 | clippy::match_wildcard_for_single_variants, 14 | clippy::if_let_mutex, 15 | unexpected_cfgs, 16 | clippy::await_holding_lock, 17 | clippy::match_on_vec_items, 18 | clippy::imprecise_flops, 19 | clippy::suboptimal_flops, 20 | clippy::lossy_float_literal, 21 | clippy::rest_pat_in_fully_bound_structs, 22 | clippy::fn_params_excessive_bools, 23 | clippy::exit, 24 | clippy::inefficient_to_string, 25 | clippy::linkedlist, 26 | clippy::macro_use_imports, 27 | clippy::option_option, 28 | clippy::verbose_file_reads, 29 | clippy::unnested_or_patterns, 30 | clippy::str_to_string, 31 | rust_2018_idioms, 32 | future_incompatible, 33 | nonstandard_style, 34 | missing_debug_implementations, 35 | missing_docs, 36 | rustdoc::missing_doc_code_examples 37 | )] 38 | #![deny(unreachable_pub)] 39 | #![forbid(unsafe_code)] 40 | 41 | mod key; 42 | mod render; 43 | mod traits; 44 | 45 | pub mod engine; 46 | 47 | pub use key::Key; 48 | pub use render::{Render, RenderHtml}; 49 | pub use traits::TemplateEngine; 50 | -------------------------------------------------------------------------------- /src/render.rs: -------------------------------------------------------------------------------- 1 | use axum::response::{Html, IntoResponse}; 2 | use serde::Serialize; 3 | 4 | use crate::TemplateEngine; 5 | 6 | /// Rendered template response 7 | /// 8 | /// Responds to the request with the rendered template and 9 | /// `text/plain; charset=utf-8` content-type 10 | /// 11 | /// # Usage 12 | /// 13 | /// ``` 14 | /// # use axum::{response::IntoResponse}; 15 | /// # use axum_template::{Render, TemplateEngine}; 16 | /// use serde::Serialize; 17 | /// 18 | /// #[derive(Serialize)] 19 | /// struct Person { /* */ } 20 | /// 21 | /// async fn handler( 22 | /// engine: impl TemplateEngine, 23 | /// ) -> impl IntoResponse { 24 | /// let key = "Template key"; 25 | /// let data = Person{ /* */ }; 26 | /// Render(key, engine, data) 27 | /// } 28 | /// ``` 29 | #[derive(Debug, Clone, PartialEq, Eq)] 30 | #[must_use] 31 | pub struct Render(pub K, pub E, pub S); 32 | 33 | impl IntoResponse for Render 34 | where 35 | E: TemplateEngine, 36 | S: Serialize, 37 | K: AsRef, 38 | { 39 | fn into_response(self) -> axum::response::Response { 40 | let Render(key, engine, data) = self; 41 | 42 | let result = engine.render(key.as_ref(), data); 43 | 44 | match result { 45 | Ok(x) => x.into_response(), 46 | Err(x) => x.into_response(), 47 | } 48 | } 49 | } 50 | 51 | /// Rendered Html response 52 | /// 53 | /// Responds to the request with the rendered template and 54 | /// `text/html` content-type 55 | /// 56 | /// # Usage 57 | /// 58 | /// ``` 59 | /// # use axum::{response::IntoResponse}; 60 | /// # use axum_template::{RenderHtml, TemplateEngine}; 61 | /// use serde::Serialize; 62 | /// 63 | /// #[derive(Serialize)] 64 | /// struct Person { /* */ } 65 | /// 66 | /// async fn handler( 67 | /// engine: impl TemplateEngine, 68 | /// ) -> impl IntoResponse { 69 | /// let key = "Template key"; 70 | /// let data = Person{ /* */ }; 71 | /// RenderHtml(key, engine, data) 72 | /// } 73 | /// ``` 74 | #[derive(Debug, Clone, PartialEq, Eq)] 75 | #[must_use] 76 | pub struct RenderHtml(pub K, pub E, pub S); 77 | 78 | impl IntoResponse for RenderHtml 79 | where 80 | E: TemplateEngine, 81 | S: Serialize, 82 | K: AsRef, 83 | { 84 | fn into_response(self) -> axum::response::Response { 85 | let RenderHtml(key, engine, data) = self; 86 | 87 | let result = engine.render(key.as_ref(), data); 88 | 89 | match result { 90 | Ok(x) => Html(x).into_response(), 91 | Err(x) => x.into_response(), 92 | } 93 | } 94 | } 95 | 96 | impl From> for RenderHtml { 97 | fn from(r: Render) -> Self { 98 | let Render(a, b, c) = r; 99 | Self(a, b, c) 100 | } 101 | } 102 | 103 | impl From> for Render { 104 | fn from(r: RenderHtml) -> Self { 105 | let RenderHtml(a, b, c) = r; 106 | Self(a, b, c) 107 | } 108 | } 109 | 110 | impl From<(K, E, S)> for Render { 111 | fn from((k, e, s): (K, E, S)) -> Self { 112 | Self(k, e, s) 113 | } 114 | } 115 | 116 | impl From<(K, E, S)> for RenderHtml { 117 | fn from((k, e, s): (K, E, S)) -> Self { 118 | Self(k, e, s) 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /src/traits.rs: -------------------------------------------------------------------------------- 1 | use axum::response::IntoResponse; 2 | use serde::Serialize; 3 | 4 | /// An abstraction over different templating engines 5 | /// 6 | /// # Implementing custom engines 7 | /// 8 | /// ``` 9 | /// # use axum_template::TemplateEngine; 10 | /// # use serde::Serialize; 11 | /// # use std::convert::Infallible; 12 | /// 13 | /// #[derive(Debug)] 14 | /// pub struct CustomEngine; 15 | /// 16 | /// impl TemplateEngine for CustomEngine { 17 | /// type Error = Infallible; 18 | /// fn render(&self, key: &str, data: S) -> Result { 19 | /// /* Render your template and return the result */ 20 | /// let result = "Hello world".into(); 21 | /// Ok(result) 22 | /// } 23 | /// } 24 | /// ``` 25 | /// 26 | /// > See the full working example [`custom_engine.rs`] 27 | /// 28 | /// [`custom_engine.rs`]: https://github.com/Altair-Bueno/axum-template/blob/main/examples/custom_engine.rs 29 | pub trait TemplateEngine { 30 | /// Error type returned if the engine is unable to process the data 31 | type Error: IntoResponse; 32 | 33 | /// Renders the template defined by the given key using the Serializable data 34 | fn render(&self, key: &str, data: S) -> Result; 35 | } 36 | -------------------------------------------------------------------------------- /tests/engine.rs: -------------------------------------------------------------------------------- 1 | #![allow(unused)] 2 | use std::marker::PhantomData; 3 | 4 | use axum::extract::FromRef; 5 | use axum::extract::FromRequest; 6 | use axum::extract::FromRequestParts; 7 | use axum_template::engine::Engine; 8 | use axum_template::TemplateEngine; 9 | use rstest::*; 10 | 11 | struct AssertImpl(pub E, PhantomData) 12 | where 13 | E: Send + Sync + TemplateEngine + FromRef; 14 | 15 | #[cfg(feature = "tera")] 16 | #[rstest] 17 | fn engine_teras_assert_impl() { 18 | AssertImpl(Engine::new(tera::Tera::default()), Default::default()); 19 | } 20 | 21 | #[cfg(feature = "handlebars")] 22 | #[rstest] 23 | fn engine_handlebars_assert_impl() { 24 | let phantom: PhantomData<()> = Default::default(); 25 | AssertImpl( 26 | Engine::new(handlebars::Handlebars::new()), 27 | Default::default(), 28 | ); 29 | } 30 | 31 | #[cfg(feature = "minijinja")] 32 | #[rstest] 33 | fn engine_minijinja_assert_impl() { 34 | let phantom: PhantomData<()> = Default::default(); 35 | AssertImpl( 36 | Engine::new(minijinja::Environment::new()), 37 | Default::default(), 38 | ); 39 | } 40 | 41 | #[cfg(feature = "minijinja-autoreload")] 42 | #[rstest] 43 | fn engine_minijinja_autoreload_assert_impl() { 44 | let phantom: PhantomData<()> = Default::default(); 45 | let jinja = minijinja_autoreload::AutoReloader::new(move |_| Ok(minijinja::Environment::new())); 46 | AssertImpl(Engine::new(jinja), Default::default()); 47 | } 48 | -------------------------------------------------------------------------------- /tests/error.rs: -------------------------------------------------------------------------------- 1 | //! Regression tests for stack overflow on IntoResponse calls for error types 2 | //! 3 | //! See https://github.com/Altair-Bueno/axum-template/issues/8 4 | 5 | #![allow(unused)] 6 | 7 | use axum::response::IntoResponse; 8 | use axum_template::engine::Engine; 9 | use axum_template::Render; 10 | use rstest::*; 11 | 12 | #[cfg(feature = "tera")] 13 | #[rstest] 14 | #[trace] 15 | #[tokio::test] 16 | async fn tera_error_into_response_check_infinite_recursion() -> anyhow::Result<()> { 17 | let engine = tera::Tera::new("./*.nothing")?; 18 | let engine = Engine::new(engine); 19 | let data = (); 20 | _ = Render("", engine, data).into_response(); 21 | Ok(()) 22 | } 23 | 24 | #[cfg(feature = "handlebars")] 25 | #[rstest] 26 | #[trace] 27 | #[tokio::test] 28 | async fn handlebars_error_into_response_check_infinite_recursion() -> anyhow::Result<()> { 29 | let engine = handlebars::Handlebars::new(); 30 | let engine = Engine::new(engine); 31 | let data = (); 32 | _ = Render("", engine, data).into_response(); 33 | Ok(()) 34 | } 35 | 36 | #[cfg(feature = "minijinja")] 37 | #[rstest] 38 | #[trace] 39 | #[tokio::test] 40 | async fn minijinja_error_into_response_check_infinite_recursion() -> anyhow::Result<()> { 41 | let engine = minijinja::Environment::new(); 42 | let engine = Engine::new(engine); 43 | let data = (); 44 | _ = Render("", engine, data).into_response(); 45 | Ok(()) 46 | } 47 | 48 | #[cfg(feature = "minijinja-autoreload")] 49 | #[rstest] 50 | #[trace] 51 | #[tokio::test] 52 | async fn minijinja_autoreload_error_into_response_check_infinite_recursion() -> anyhow::Result<()> { 53 | let jinja = minijinja_autoreload::AutoReloader::new(move |_| Ok(minijinja::Environment::new())); 54 | let engine = Engine::new(jinja); 55 | let data = (); 56 | _ = Render("", engine, data).into_response(); 57 | Ok(()) 58 | } 59 | -------------------------------------------------------------------------------- /tests/key.rs: -------------------------------------------------------------------------------- 1 | use axum::{body::Body, http::Request, routing::get, Router}; 2 | use axum_template::Key; 3 | use rstest::*; 4 | use speculoos::prelude::*; 5 | use tower::util::ServiceExt; 6 | 7 | #[rstest] 8 | #[case("/", "/")] 9 | #[case("/{hello}", "/world")] 10 | #[case("/{hello}", "/guys")] 11 | #[trace] 12 | #[tokio::test] 13 | async fn key_extracts_from_request_route_path( 14 | #[case] route: &'static str, 15 | #[case] uri: &'static str, 16 | ) -> anyhow::Result<()> { 17 | let router: Router = Router::new().route( 18 | route, 19 | get(move |Key(key): Key| async move { assert_that!(key.as_str()).is_equal_to(route) }), 20 | ); 21 | 22 | let _response = router 23 | .oneshot(Request::builder().uri(uri).body(Body::empty())?) 24 | .await?; 25 | 26 | Ok(()) 27 | } 28 | 29 | #[rstest] 30 | #[trace] 31 | #[tokio::test] 32 | async fn key_impl_asref_str() { 33 | fn inner(_: impl AsRef) {} 34 | inner(Key("Some String".into())); 35 | } 36 | -------------------------------------------------------------------------------- /tests/render.rs: -------------------------------------------------------------------------------- 1 | use std::convert::Infallible; 2 | 3 | use axum::response::IntoResponse; 4 | use axum_template::{Render, RenderHtml, TemplateEngine}; 5 | use rstest::*; 6 | 7 | #[derive(Debug, Clone, Default)] 8 | pub struct MockEngine; 9 | 10 | impl TemplateEngine for MockEngine { 11 | type Error = Infallible; 12 | 13 | fn render(&self, _: &str, _: S) -> Result { 14 | Ok("".to_owned()) 15 | } 16 | } 17 | 18 | #[fixture] 19 | fn engine() -> MockEngine { 20 | MockEngine 21 | } 22 | 23 | #[rstest] 24 | #[trace] 25 | #[tokio::test] 26 | async fn render_responds_with_text_plain( 27 | engine: impl TemplateEngine, 28 | #[values("")] key: &str, 29 | #[values(())] data: (), 30 | ) -> anyhow::Result<()> { 31 | let response = Render(key, engine, data).into_response(); 32 | 33 | let (parts, _) = response.into_parts(); 34 | let content_type = parts 35 | .headers 36 | .get(axum::http::header::CONTENT_TYPE) 37 | .unwrap() 38 | .as_bytes(); 39 | 40 | assert_eq!(content_type, b"text/plain; charset=utf-8"); 41 | Ok(()) 42 | } 43 | 44 | #[rstest] 45 | #[trace] 46 | #[tokio::test] 47 | async fn render_html_responds_with_text_html( 48 | engine: impl TemplateEngine, 49 | #[values("")] key: &str, 50 | #[values(())] data: (), 51 | ) -> anyhow::Result<()> { 52 | let response = RenderHtml(key, engine, data).into_response(); 53 | 54 | let (parts, _) = response.into_parts(); 55 | let content_type = parts 56 | .headers 57 | .get(axum::http::header::CONTENT_TYPE) 58 | .unwrap() 59 | .as_bytes(); 60 | 61 | assert_eq!(content_type, b"text/html; charset=utf-8"); 62 | Ok(()) 63 | } 64 | --------------------------------------------------------------------------------