Skip to content
thearyanahmedPublic

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

monotype

Templating for rust, inspired by Laravel Blade .

Blade's syntax — @extends, @section, @foreach, <x-alert>, {{ }} — over real Rust expressions, type-checked by rustc instead of interpreted at runtime.

{{-- templates/posts/index.ono --}}
@extends('layouts/app.ono')

@section('content')
  <x-alert type="error" :message="error" />

  @foreach (post in posts)
    <article>
      <h2>{{ loop.iteration }}. {{ post.title }}</h2>
      {!! post.body_html !!}
    </article>
  @empty
    <p>Nothing here yet.</p>
  @endforeach
@endsection

@push('head')<link rel="stylesheet" href="/posts.css">@endpush
use monotype::Template;

#[derive(Template)]
#[template(path = "posts/index.ono")]
struct PostsIndex {
    posts: Vec<Post>,
    error: String,
}

let html = PostsIndex { posts, error }.render()?;

Install

[dependencies]
monotype = "0.1"
monotype = { version = "0.1", features = ["axum"] }   # adds View<T>: IntoResponse
monotype = { version = "0.1", features = ["json"] }   # adds @json

Templates live in <crate>/templates/; override the directory with MONOTYPE_TEMPLATE_DIR.

The .ono extension is convention, not a rule — paths in #[template(path = …)], @include and @extends are opaque strings, so name them whatever you like. foo.ono.html is worth considering if you want your editor to syntax-highlight them as HTML.

Examples

cargo run --features axum --example blog     # a blog: articles, tags, threaded comments
cargo run --features axum --example server   # the smaller tour of the directives
cargo run --release --example bench
PORT=8080 cargo run --features axum --example blog   # if 3000 is taken

examples/blog.rs is the realistic one: an article list, an article page with a threaded comment tree, tag pages, a comment form that redirects back with a flash, and a 404 — all on static data.

examples/server.rs is a smaller tour: layout inheritance (@extends, @section, @yield, @section…@show, @parent), a partial with its own data, @push into a @stack in <head>, loop, components with props, a named slot and an attribute bag, @class, and an enum template with one file per variant.

Fragments

For htmx and Turbo: name a part of a template and render just that part, without a second template that duplicates the markup.

@fragment('comments')
  <section id="comments">…</section>
@endfragment
page.render()?;              // the whole page
page.fragment_comments()?;   // just that section
page.render_fragment("comments")?;   // by name — Option<String>, for content negotiation

The methods are generated, so a typo in a fragment name is a compile error. Unlike Blade — which renders the whole view and returns the captured slice — a fragment here renders only its own subtree: in the blog example that is 861 bytes instead of 6131.

A fragment must sit where the only data in scope is the template's own fields. Inside a @foreach, or inside an @include that was passed extra data, there is nothing sensible to render alone, and it is a compile error that says so.

Recursion

@include is inlined at compile time, so a template that includes itself would expand forever — it is rejected as a cycle. Recursion goes through @render instead, which writes another Template value into the same buffer. That is an ordinary runtime call, so it terminates on the data, exactly like Blade's runtime @include:

{{-- templates/comment.ono --}}
<div class="comment">
  <p>{{ comment.body }}</p>
  @foreach (reply in comment.replies)
    @render(CommentThread { comment: reply })
  @endforeach
</div>
#[derive(Template)]
#[template(path = "comment.ono")]
struct CommentThread<'a> { comment: &'a Comment }

No intermediate String, and a @push inside the nested template lands in the outer render's stacks. examples/blog.rs renders its comment thread this way.

How it differs from Blade

Everything inside {{ }} and directive parentheses is Rust, not PHP:

Blade monotype
{{ $post->title }} {{ post.title }}
@foreach ($posts as $post) @foreach (post in posts)
@if ($count > 10) @if (*count > 10) — fields bind by reference
$loop->first loop.is_first — Rust naming for booleans
$loop->parent->iteration loop.parent.unwrap().iteration — it's an Option
view('x', ['a' => 1]) X { a: 1 } — data is a struct, not a map
@php $x = 1; @endphp @let x = 1;

Everything resolves at compile time: a layout, its sections, its partials and its components all inline into one function. There is no view finder, no section registry, no component registry, and no dynamic dispatch — a missing template, a missing prop, or a typo in an expression is a build error. A changed template triggers a rebuild, but there is no hot reload.

Enums

One template per variant. The variant's fields are that template's locals.

#[derive(Template)]
enum Notice {
    #[template(path = "notice/info.ono")]
    Info { message: String },
    #[template(path = "notice/error.ono")]
    Error { message: String, code: u16 },
    #[template(path = "notice/silent.ono")]
    Silent,
}

A #[template] on the enum itself is the fallback for variants that don't name one.

Components

<x-alert> resolves to templates/components/alert.ono (or alert/index.ono); <x-forms.input> to components/forms/input.ono.

{{-- templates/components/alert.ono --}}
@props(type = "info", message)
<div class="alert-{{ type }}"{{ attributes.merge("role", "alert") }}>
  {{ message }}
  {{ slot }}
</div>
<x-alert :message="msg" />
<x-alert type="error" :message="msg" id="a1">extra body</x-alert>
  • @props declares names and defaults — no type annotations, the types come from the call site.
  • type="x" is text (with {{ }} interpolation), :type="expr" is a Rust expression, a bare required is its own value.
  • A bound value is passed like any Rust value, so a non-Copy field needs a borrow: :message="&row.name", not :message="row.name".
  • Undeclared attributes land in attributes, with merge, get, has, only, except.
  • The tag body is slot; <x-slot:footer>…</x-slot> binds footer.
  • {{ slot }} and {{ attributes }} are written raw; everything else is HTML-escaped.
  • A component that never mentions slot or attributes is not given them, so it costs the same as writing the markup by hand. Content passed to a component that ignores its slot is therefore never rendered — including any @push inside it.
  • @aware(name) is a no-op: a component body is inlined as a block, so an enclosing component's bindings are already in scope. Declared props shadow them.

Directives

{{ }} {{{ }}} {!! !!} {{-- --}} @verbatim @{{ }} @@ · @if @elseif @else @unless @switch @case @default · @foreach @empty @forelse @for @while @break @continue · @let · @include @includeIf @includeWhen @includeUnless @includeFirst @each · @extends @section @endsection @stop @show @yield @parent @hasSection @sectionMissing · @stack @push @prepend @pushOnce @prependOnce @once · @props @aware <x-…> <x-slot:…> @render @fragment · @class @style @checked @selected @disabled @required @readonly · @json (feature json) — <, >, &, ' are hex-escaped, so it is safe in a <script> body but not in an HTML attribute

<span @class("btn", "btn-active" => *active, size)>   {{-- class="btn btn-active lg" --}}
<input@checked(*on)@disabled(!*on)>                    {{-- <input checked> --}}

@switch compiles to match, so @case takes a pattern — and with no @default there is no catch-all arm, which means rustc still checks exhaustiveness.

Not ported: <x-dynamic-component>, @php, and the framework-coupled directives (@csrf, @error, @auth, @can, @vite, …), which belong in an integration crate rather than here.

Whitespace

Output is byte-for-byte what the template says, as in Blade — a directive on its own line leaves that line's newline behind. Irrelevant for HTML, not for plain text, so it is opt-in per template:

#[derive(Template)]
#[template(path = "mail/welcome.ono", trim = true)]
struct Welcome { name: String }

trim = true drops the newline after a block directive and the indentation before one — Jinja's trim_blocks + lstrip_blocks. Echoes, components and @class-style inline directives are left alone. The flag applies to every partial, layout and component pulled into that template.

The loop variable

Available inside @foreach, and generated only if the body mentions it — otherwise the loop compiles to a plain for.

index  iteration  count  remaining  is_first  is_last  is_even  is_odd  depth  parent

count, remaining and is_last need the iterator's length, so those loops require an ExactSizeIterator.

License

MIT — see LICENSE.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages