#template #generation #injection #tera #micro-framework #declarative

rrgen

A microframework for declarative code generation and injection

8 releases (4 breaking)

0.5.3 Dec 11, 2023
0.5.2 Nov 30, 2023
0.4.0 Nov 21, 2023
0.3.0 Nov 21, 2023
0.1.0 Nov 20, 2023

#252 in Template engine

Download history 4829/week @ 2024-07-29 5346/week @ 2024-08-05 4949/week @ 2024-08-12 5397/week @ 2024-08-19 5845/week @ 2024-08-26 1907/week @ 2024-09-02 2274/week @ 2024-09-09 3913/week @ 2024-09-16 5461/week @ 2024-09-23 6653/week @ 2024-09-30 7673/week @ 2024-10-07 8799/week @ 2024-10-14 8941/week @ 2024-10-21 10029/week @ 2024-10-28 11038/week @ 2024-11-04 9506/week @ 2024-11-11

40,829 downloads per month
Used in 6 crates (2 directly)

Apache-2.0

18KB
263 lines

rrgen

A microframework for declarative code generation and injection.

Getting started

Templates use Tera as a templating language (similar to liquid), and use a special metadata/body separation with frontmatter.

The first part of the template instructs what the template should do, and which injections it should perform.

The second part is the actual target file that's being generated.

Example template controller.t:

---
to: tests/fixtures/realistic/generated/controllers/{{name | snake_case }}.rs
injections:
- into: tests/fixtures/realistic/generated/controllers/mod.rs
  append: true
  content: "pub mod {{ name | snake_case }};"
- into: tests/fixtures/realistic/generated/app.rs
  after: "AppRoutes::"
  content: "            .add_route(controllers::{{ name | snake_case }}::routes())"
---
#![allow(clippy::unused_async)]
use axum::{extract::State, routing::get};
use rustyrails::{
    app::AppContext,
    controller::{format, Routes},
    Result,
};

pub async fn echo(req_body: String) -> String {
    req_body
}

pub async fn hello(State(ctx): State<AppContext>) -> Result<String> {
    // do something with context (database, etc)
    format::text("hello")
}

pub fn routes() -> Routes {
    Routes::new()
        .prefix("{{ name | snake_case }}")
        .add("/", get(hello))
        .add("/echo", get(echo))
}

Rendering a template will create one or more files, potentially inject into files, and is done like so:

use std::fs;
use rrgen::Rgen;
use serde_json::json;

let rrgen = RRgen::default();
let vars = json!({"name": "post"});

rrgen.generate(
    &fs::read_to_string("tests/fixtures/test1/template.t").unwrap(),
    &vars,
)
.unwrap();

vars will be variables that are exposed both for the frontmatter part and the body part.

Dependencies

~9–18MB
~245K SLoC