What is it

html provides an Html type and a template processor which produces Html and auto-escapes any embedded values.

Why use it

Before template processors, your options for producing html were to

The first option is the most widespread, but means that your logic for filling in the template won't be co-located with the contents of the template itself. It also gives a damp and dimly-lit surface for "template languages" to grow. These are often full programming languages in their own right and require special IDE support.

The second option isn't as popular because you effectively lose the ability to apply the expertise of designers, who are generally familiar with HTML and are used to seeing page layout expressed in HTML. It also puts a lot of pressure on the programmatic API, since you need to make sure every HTML idiom you need to express is expressible. A difficult feat with an evolving standard.

Template processors are a middle ground of sorts.

They are a templating language but, because they will be an official part of Java, you can count on IDE support and will be able to collocate them with the code for filling in values.

They are a programmatic API but, because you write HTML directly, every idiom is expressible. It should be familiar to most designers as well.

You could reasonably draw a parallels between this approach and JSX from the JavaScript world.

Getting Started

At time of writing template processors are a preview-feature, so you will need to use the latest version of the library and the latest JDK.

import java.util.List;
import java.util.ArrayList;

import dev.mccue.html.Html;
import static dev.mccue.html.Html.HTML;

void main() {
    String name = "joe";
    var pets = List.of("snoopy", "Yellow Bird");
    var petHtml = new ArrayList<Html>();
    for (var pet : pets) {
        petHtml.add(HTML."<li> \{pet} </li>");
    var page = HTML."""
            <h1> Hello \{name} </h1>

<- Index