Smeltery
Get started

The basics

v0.1

Mold templates

Views are resources/views/<name>.mold.html files with an @-directive syntax. A struct with #[derive(Mold)] names its template; its fields are the template's variables. A handler returns the struct (or Result<TheStruct>):

rust
use smeltery::prelude::*;

#[derive(Mold)]
#[mold("posts/index")]          // resources/views/posts/index.mold.html
pub struct PostsIndex {
    pub title: String,
    pub posts: Vec<Post>,       // fields implement serde::Serialize
}

async fn index() -> Result<PostsIndex> {
    Ok(PostsIndex { title: "Posts".into(), posts: load_posts().await? })
}
text
@extends("layouts/app")

@section("title", title)

@section("content")
<h1>{{ title }}</h1>
@for(post in posts)
  <x-card :title="post.title">
    <a href="{{ route("posts.show", { post: post.id }) }}">Read</a>
  </x-card>
@empty
  <p>No posts yet.</p>
@endfor
@endsection
Syntax Does
{{ expr }} / {!! expr !!} output, HTML-escaped / raw
{{-- … --}} comment, not rendered
@{{ / @@ a literal {{ / @
@if(expr) @elseif(expr) @else @endif, @unless(expr) @endunless conditions
@for(x in items) @empty @endfor, @for(key, value in map), @for x in items loops; loop.index, loop.index0, loop.first, loop.last, loop.count
@extends("layouts/app"), @section("name") … @endsection, @section("name", expr), @yield("name", "default") layouts
@include("partials/nav", { key: expr }) include another template; it sees the current variables plus the given ones
<x-alert type="error" :count="n">body</x-alert>, <x-forms.input /> components from resources/views/components/ (forms/input); string attributes, :attr expressions, the body as {{ slot }}, named slots with @slot("title") … @endslot
@csrf, @method("PUT") hidden _token and _method form fields
@error("field") … @enderror the body with {{ message }} when the field has a validation error
@auth … @else … @endauth, @guest … @endguest by sign-in state
@spark("counter", { start: 5 }), @sparksScripts a live component and the Sparks runtime (see Sparks)

Expressions have ||, &&, == != < <= > >=, + - * / %, !, field access a.b, indexing a[i], string, number, true/false/null literals, the filters upper, lower, trim, title, len, default(x), join(sep), json and url ({{ name | upper }}), and the functions route("name", { param: expr }), old("field"), session("key") (a session value as text, "" when missing) and csrf_token(). false, 0, "", empty lists, and None are falsy. A line holding only a block directive leaves no blank line in the output. An @word that is not a directive (@media) stays text, and an @ right after an ASCII letter, digit or _ never starts a directive, so e-mail addresses (me@auth.example) stay text too.

{{ }} escapes & < > " ', which is right for text and for quoted attribute values. A value that becomes JavaScript or a link takes a filter:

  • json writes the value (text, a number, a list, a struct) as a JavaScript literal in which <, >, &, ', U+2028 and U+2029 are \u escapes. In an attribute whose value runs as JavaScript (x-data, @click, x-init, onclick, the arguments of wire:click) write {{ value | json }} without quotes around it: x-data="{ name: {{ user.name | json }} }", wire:click="remove({{ post.id | json }}, {{ post.slug | json }})". Inside a <script> element write {!! value | json !!}, because the browser does not decode &quot; there: <script>const post = {!! post | json !!};</script>. Text echoed between quotes in JavaScript ('{{ name }}') is not safe: the browser turns &#39; back into ' before the code runs.
  • url keeps a relative URL and an http:, https:, mailto: or tel: URL, and writes # for any other (javascript:, data:), and for a value with an &, a byte-order mark or a control character before its first /, ? or # (an entity such as &#58; hides a scheme): <a href="{{ link | url }}">.
  • Attribute values are quoted (class="{{ name }}"): an unquoted value ends at the first space of the text.
  • {!! !!} never goes into an attribute: it writes " as it is. In attributes use {{ }} (with json or url); {!! v | json !!} belongs inside <script> only.

Two modes, same output:

  • Debug builds read the templates at runtime from <root>/resources/views and re-read a file when it changes, so an edit shows on the next request without recompiling.
  • Release builds run Rust code generated from the templates at compile time. A template variable without a matching field, a syntax error and a missing template are compile errors naming the .mold.html file and line.

A template error while rendering (for example a division by zero) answers 500. With APP_DEBUG=true the page shows the file, line, column and the lines around it; otherwise it is the normal error page and the details go to the log.

The values @csrf, @auth, @guest, @error, old() and session() read come from smeltery::view::ViewData, which the session middleware of web routes fills (see Sessions). On API routes there is no session: @csrf is a render error there and @auth renders its @else branch. route() uses the app's named routes.

↑↓ moveEnter openEsc close