Hiccup html templating in rust

Overview

Hiccup

Build Status

A Clojure's Hiccup inspired macro. At the moment support for inline code execution is not guaranteed. The main objective of this lib is to prevent unclosed html tags.

Basic elements:

The macro `hiccup! receives a mutable string as the first argument and mutates the string to emit the HTML. The order of the elements is:

  1. tag as the first element.
  2. Optional attribute inside the tag should follow the tag name as {attribute1=>"value1 value2 ... valuen", attr=>"value"}. Also, the attributes should be inside {...} and separate each key value pair by ,. The element should be written as key=>"value", where key is a symbol, followed by an arrow (=>), and then the value as a string "value".
  3. After (Optional) the tag name or the attributes {...} you could include [...] that can have other tags, such as p["text"] or regular string values.
  4. Inside the [...] you also can substitute your string for some simple rust code inside a (...). This can bem something like p[format!("{:?}", 3 + 4)] or div[(x)] where x was defined in the outside.

Differences between Clojure and Rust Hiccup:

  • Clojure: [:a {:href "http://github.com"} "GitHub"]
  • Rust: a{href=>"http://github.com"}["GitHub"]

Usage

Add dependency to Cargo.toml:

[dependencies]
hiccup = "0.2.5"

Code example with hiccup! macro:

use hiccup::hiccup;

fn main() {
    let mut html = String::new();

    let _ = hiccup!(&mut html,
        html[
            head[meta{name=>"author", content=>"Julia Naomi"}
                title["Hiccup guide"]]
            body{class=>"amazing hiccup guide"}[
                h1{font=>"bold", color=>"red"}["Hiccup is the best!"]
                p["please lookup clojure's hiccup for better ideas on this macro"]]
        ]);

    assert_eq!(html,"<html><head><meta name=\"author\" content=\"Julia Naomi\"/>\
    <title>Hiccup guide</title></head><body class=\"amazing hiccup guide\">\
    <h1 font=\"bold\" color=\"red\">Hiccup is the best!</h1>\
    <p>please lookup clojure\'s hiccup for better ideas on this macro</p></body></html>");
}

With remote code execution:

let mut html_inner = String::new();
let mut html_outer = String::new();
let x = "inner my str";
let y = "my str2";
let z = "my str3";

let _ = hiccup!(&mut html_inner,
    div[
        div{hello=>"inner world"}[(x)]
    ]
);

let _ = hiccup!(&mut html_outer,
    html[
        body{class=>"amazing hiccup guide"}[
            p["please lookup clojure's hiccup for better ideas on this macro"]
            div[
                div{hello=>"world"}[(html_inner)]
                div[(y.to_owned() + " " + z)]
                p["bye"]
            ]
        ]
    ]);

assert_eq!(html_outer,"<html><body class=\"amazing hiccup guide\">\
<p>please lookup clojure\'s hiccup for better ideas on this macro</p>\
<div><div hello=\"world\"><div><div hello=\"inner world\">inner my str</div></div></div>\
<div>my str2 my str3</div><p>bye</p></div></body></html>");

FAQs

  1. Is it possible tu use this lib as an XML templating?

Yes, I added a more generic XML case to the tests recently

fn main() {
    let mut out = String::new();

    let _ = hiccup!(&mut out,
        xml{metas=>"I forgot them all", version=>"any version"}[
            family[name{name=>"Rubiechiov", origin=>"Kazakhstan"}]
            members{class=>"close family"}[
                member{age=>"oldest", color=>"yellow"}["some name"]
                member{age=>"mid-age", color=>"yellow"}["some other name"]
                member{age=>"yougest", color=>"brown"}["Julia"]]
        ]);

    assert_eq!(out,"<xml metas=\"I forgot them all\" version=\"any version\"><family>\
    <name name=\"Rubiechiov\" origin=\"Kazakhstan\"/></family><members class=\"close family\">\
    <member age=\"oldest\" color=\"yellow\">some name</member>\
    <member age=\"mid-age\" color=\"yellow\">some other name</member>\
    <member age=\"yougest\" color=\"brown\">Julia</member></members></xml>");
}

Contribution

Add the feature you included in the macro as the name of the PR with tests

Thanks to

@otaviopace

You might also like...
A template for a Rust-powered static-page Try Online interface

rust-tio-template A template for a Rust-powered static-page Try Online interface What is included This is an example setup that enables all of the fol

MiniJinja is a powerful but minimal dependency template engine for Rust
MiniJinja is a powerful but minimal dependency template engine for Rust

MiniJinja: a powerful template engine for Rust with minimal dependencies MiniJinja is a powerful but minimal dependency template engine for Rust which

Templates for creating rust projects with a GitHub-managed lifecycle with cargo-generate 🏗️📃

rust-templates Templates for creating rust projects with a GitHub-managed lifecycle with cargo-generate. 🏗️ 📃 What you get: PR build validation usin

A "Hello, world!" template of a Rust binary crate for the ESP-IDF framework.

Rust on ESP-IDF "Hello, World" template A "Hello, world!" template of a Rust binary crate for the ESP-IDF framework. This is the crate you get when ru

A fast & simple boilerplate generator, built with Rust. 🦀
A fast & simple boilerplate generator, built with Rust. 🦀

Boom 💥 A fast & simple boilerplate generator, built with Rust. Installing boom This package is not yet downloadable on Brew or other package managers

A template for creating services in Rust using Axum and Prisma.

A template for creating services in Rust using Axum and Prisma. This uses the super cool Prisma Rust Client.

✨ A perfect template for a binary rust project.

Rust Template A project template for Rust, helping to structure your projects blazingly fast ⚡ . Features 🔥 Code-ready for binary projects. Add amazi

A PostgreSQL extension for rendering the Tera HTML templating language.

PGTera PGTera is a PostgreSQL extension that provides functions for using Tera to render HTML templates. When used with a tool like Postgrest, you can

Like jq, but for HTML. Uses CSS selectors to extract bits content from HTML files.

Like jq, but for HTML. Uses CSS selectors to extract bits content from HTML files. Mozilla's MDN has a good reference for CSS selector syntax.

Distribute a wasm SPA as HTML by wrapping it as a polyglot "html+wasm+zip"

A packer that adds a webpage to WASM module, making it self-hosted! Motivation At the moment, Browsers can not execute WebAssembly as a native single

Rust templating with Handlebars

handlebars-rust Handlebars templating language implemented in Rust and for Rust. Handlebars-rust is the template engine that renders the official Rust

Rust templating with Handlebars

handlebars-rust Handlebars templating language implemented in Rust and for Rust. Handlebars-rust is the template engine that renders the official Rust

A blazingly fast static web server with routing, templating, and security in a single binary you can set up with zero code. :zap::crab:
A blazingly fast static web server with routing, templating, and security in a single binary you can set up with zero code. :zap::crab:

binserve ⚡ 🦀 A blazingly fast static web server with routing, templating, and security in a single binary you can set up with zero code. 🔥 UPDATE: N

Easily embed and manage assets for your web application to build standalone-executables. Offers filename hashing, templating and more.

reinda: easily embed and manage assets This library helps you manage your assets (external files) and is mostly intended to be used in web application

tpp (Tera Pre-Processor) is a versatile CLI (Command Line Interface) tool crafted for preprocessing files using the Tera templating engine.

tpp (Tera Pre-Processor) is a versatile CLI (Command Line Interface) tool crafted for preprocessing files using the Tera templating engine. Drawing inspiration from pre-processors like cpp and gpp, tpp is the next evolution with its powerful expressive toolset.

A library for extracting #[no_mangle] pub extern "C" functions (https://docs.rust-embedded.org/book/interoperability/rust-with-c.html#no_mangle)

A library for extracting #[no_mangle] pub extern "C" functions In order to expose a function with C binary interface for interoperability with other p

A HTML entity encoding library for Rust

A HTML entity encoding library for Rust Example usage All example assume a extern crate htmlescape; and use htmlescape::{relevant functions here}; is

Rust crate for scraping URLs from HTML pages

url-scraper Rust crate for scraping URLs from HTML pages. Example extern crate url_scraper; use url_scraper::UrlScraper; fn main() { let director

:pencil: Compile-time HTML templates for Rust

maud Documentation (source) • API reference • Change log Maud is an HTML template engine for Rust. It's implemented as a macro, html!, which compiles

Owner
Julia Naomi
Rust, Games, Kotlin, Elixir
Julia Naomi
Easily embed and manage assets for your web application to build standalone-executables. Offers filename hashing, templating and more.

reinda: easily embed and manage assets This library helps you manage your assets (external files) and is mostly intended to be used in web application

Lukas Kalbertodt 23 Jul 15, 2022
:pencil: Compile-time HTML templates for Rust

maud Documentation (source) • API reference • Change log Maud is an HTML template engine for Rust. It's implemented as a macro, html!, which compiles

Chris Wong 1.4k Jan 1, 2023
A macro-based html builder for rust

Horrorshow A macro-based html templating library, compatible with stable rust (currently requires rust >= 1.37). Features This crate will degrade grac

Steven Allen 267 Dec 11, 2022
Balsa is a delightfully simple HTML template engine

?? balsa Balsa is a delightfully simple HTML template engine. It is designed to be used in user interfaces such as a CMS where a user needs to be able

Tyler Lafayette 1 Jan 19, 2022
Yarte stands for Yet Another Rust Template Engine

Should we start to worry? bytes-buf feature can produce SIGILL. avx and sse flags are in almost all cpus of x86 and x86_64 architectures. More details

Juan Aguilar 249 Dec 19, 2022
Rust Compiled Templates with static-file handling

Rust Compiled Templates — ructe This is my attempt at writing a HTML template system for Rust. Some inspiration comes from the scala template system u

Rasmus Kaj 337 Jan 8, 2023
A template engine for Rust based on Jinja2/Django

Tera Tera is a template engine inspired by Jinja2 and the Django template language. <title>{% block title %}{% endblock title %}</title> <ul> {% for u

Vincent Prouillet 2.5k Jan 1, 2023
Type-safe, compiled Jinja-like templates for Rust

Askama Askama implements a template rendering engine based on Jinja. It generates Rust code from your templates at compile time based on a user-define

Dirkjan Ochtman 2k Jan 5, 2023
A flexible template engine for Rust

Rustache Rustache is a Rust implementation of the Mustache spec. Documentation The different Mustache tags are documented at the mustache(5) man page.

rustache 208 May 10, 2022
A minimalist Rust WebAssembly project template

MiniWASM - A minimalist Rust WebAssembly project template This is a minimal Rust-powered WebAssembly application template. It was designed to showcase

Emil Loer 160 Jul 26, 2022