Skip to content

Commit

Permalink
chore(examples): add rinja template (#148)
Browse files Browse the repository at this point in the history
  • Loading branch information
fundon authored Oct 3, 2024
1 parent 99c42ac commit 0e61158
Show file tree
Hide file tree
Showing 5 changed files with 90 additions and 0 deletions.
1 change: 1 addition & 0 deletions examples/templates/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,6 @@
* [maud](maud)
* [minijinja](minijinja)
* [tera](tera)
* [rinja](rinja)

[Here]: https://github.com/rosetta-rs/template-benchmarks-rs
13 changes: 13 additions & 0 deletions examples/templates/rinja/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
[package]
name = "rinja-template-example"
version = "0.1.0"
edition.workspace = true
publish = false

[dependencies]
viz.workspace = true

serde.workspace = true
tokio = { workspace = true, features = ["rt-multi-thread", "macros"] }

rinja = { version = "0.3" }
57 changes: 57 additions & 0 deletions examples/templates/rinja/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
#![allow(clippy::unused_async)]

use std::net::SocketAddr;

use rinja::Template;
use serde::Serialize;
use tokio::net::TcpListener;
use viz::{serve, Error, Request, Response, ResponseExt, Result, Router};

#[allow(dead_code)]
#[derive(Template)]
#[template(path = "index.html")]
struct Tmpl<'a> {
title: &'a str,
users: Vec<User<'a>>,
}

#[derive(Serialize)]
struct User<'a> {
url: &'a str,
username: &'a str,
}

async fn index(_: Request) -> Result<Response> {
let body = Tmpl {
title: "Viz.rs",
users: vec![
User {
url: "https://github.com/rust-lang",
username: "rust-lang",
},
User {
url: "https://github.com/viz-rs",
username: "viz-rs",
},
],
}
.render()
.map_err(Error::boxed)?;

Ok(Response::html(body))
}

#[tokio::main]
async fn main() -> Result<()> {
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
let listener = TcpListener::bind(addr).await?;
println!("listening on http://{addr}");

let app = Router::new().get("/", index);

if let Err(e) = serve(listener, app).await {
println!("{e}");
}

Ok(())
}
9 changes: 9 additions & 0 deletions examples/templates/rinja/templates/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{% extends "layout.html" %}
{% block title %} Viz & Rinja {% endblock %}
{% block body %}
<ul>
{% for user in users %}
<li><a href="{{ user.url }}">{{ user.username }}</a></li>
{% endfor %}
</ul>
{% endblock %}
10 changes: 10 additions & 0 deletions examples/templates/rinja/templates/layout.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<html>
<head>
<title>
{% block title %}{% endblock %}
</title>
</head>
<body>
{% block body %}{% endblock %}
</body>
</html>

0 comments on commit 0e61158

Please sign in to comment.