Java Clean Architecture Masterclass

Java Clean Architecture MasterclassNov 20-21

Join

Test Status

pug4j - a pug implementation written in Java

pug4j's intention is to be able to process pug templates in Java without the need of a JavaScript environment, while being fully compatible with the original pug syntax.

pug4j was formerly known as jade4j. Because of the naming change of the javascript version and the alignment to the featureset of pug.js (https://pugjs.org/) we decided to switch the name.

Contents

Example

index.pug

doctype html
html
  head
    title= pageName
  body
    ol#books
      for book in books
        if book.available
          li #{book.name} for #{book.price} €

Java model

List<Book> books = new ArrayList<Book>();
books.add(new Book("The Hitchhiker's Guide to the Galaxy", 5.70, true));
books.add(new Book("Life, the Universe and Everything", 5.60, false));
books.add(new Book("The Restaurant at the End of the Universe", 5.40, true));

Map<String, Object> model = new HashMap<String, Object>();
model.put("books", books);
model.put("pageName", "My Bookshelf");

Running the above code through String html = Pug4J.render("./index.pug", model) will result in the following output:

<!DOCTYPE html>
<html>
  <head>
    <title>My Bookshelf</title>
  </head>
  <body>
    <ol id="books">
      <li>The Hitchhiker's Guide to the Galaxy for 5,70 €</li>
      <li>The Restaurant at the End of the Universe for 5,40 €</li>
    </ol>
  </body>
</html>

Syntax

See also the original https://github.com/pugjs/pug#syntax.

Usage

via Maven

Just add following dependency definitions to your pom.xml.

<dependency>
  <groupId>de.neuland-bfi</groupId>
  <artifactId>pug4j</artifactId>
  <version>3.0.0-alpha-2</version>
</dependency>

Build it yourself

Clone this repository ...

git clone https://github.com/neuland/pug4j.git

... build it using maven ...

cd pug4j
mvn install

... and use the pug4j-2.x.x.jar located in your target directory.

Simple static API

The simple static API provides the easiest way to render templates in one step:

String html = Pug4J.render("./index.pug", model);

With pretty printing:

String html = Pug4J.render("./index.pug", model, true);

Streaming output using a java.io.Writer:

Pug4J.render("./index.pug", model, writer);

Note: For production use with template reuse, use the Full API below which provides caching and more control.

Full API

For production use, create a PugEngine instance with the builder pattern. This separates template loading/caching (engine) from render-time settings (context).

Quick setup:

PugEngine engine = PugEngine.forPath("/templates/");
PugTemplate template = engine.getTemplate("index.pug");
String html = engine.render(template, model);

Advanced configuration:

// Configure template loading
FileTemplateLoader loader = new FileTemplateLoader("/root/dir/");
loader.setBase("base/path");

// Build engine with settings
PugEngine engine = PugEngine.builder()
    .templateLoader(loader)
    .caching(true)
    .build();

// Get template (cached automatically)
PugTemplate template = engine.getTemplate("index.pug");

// Prepare model
Map<String, Object> model = new HashMap<>();
model.put("company", "neuland");

// Render with default settings
String html = engine.render(template, model);

// Or with custom render context
RenderContext context = RenderContext.builder()
    .prettyPrint(true)
    .defaultMode(Pug4J.Mode.HTML)
    .build();

String prettyHtml = engine.render(template, model, context);

Key concepts:

Caching

PugEngine handles template caching automatically. If you request the same unmodified template twice, you'll get the same instance and avoid unnecessary parsing.

PugTemplate t1 = engine.getTemplate("index.pug");
PugTemplate t2 = engine.getTemplate("index.pug");
t1.equals(t2) // true

Clear the template and expression cache:

engine.clearCache();

Configure caching at build time:

PugEngine engine = PugEngine.builder()
    .caching(false)  // Disable for development
    .maxCacheSize(500)  // Limit cache size
    .expressionCacheSize(1000)  // Configure expression cache
    .build();

Output Formatting

By default, Pug4J produces compressed HTML without unneeded whitespace. You can enable pretty printing using RenderContext:

RenderContext context = RenderContext.builder()
    .prettyPrint(true)
    .build();

String html = engine.render(template, model, context);

Pug detects if it has to generate (X)HTML or XML code by your specified doctype.

If you are rendering partial templates that don't include a doctype, pug4j generates HTML code. You can set the defaultMode manually:

RenderContext context = RenderContext.builder()
    .defaultMode(Pug4J.Mode.HTML)   // <input checked>
    .defaultMode(Pug4J.Mode.XHTML)  // <input checked="true" />
    .defaultMode(Pug4J.Mode.XML)    // <input checked="true"></input>
    .build();

Filters

Filters allow embedding content like markdown into your pug template:

:markdown
  # headline
  hello **world**

will generate

<h1>headline</h1>
<p>hello <strong>world</strong></p>

pug4j comes with built-in cdata, css, and js filters. You can add custom filters when building your engine:

PugEngine engine = PugEngine.builder()
    .filter("markdown", new MarkdownFilter())
    .build();

To implement your own filter, you have to implement the Filter Interface. If your filter doesn't use any data from the model you can inherit from the abstract CachingFilter and also get caching for free. See the neuland/jade4j-coffeescript-filter project as an example.

Helpers

If you need to call custom java functions the easiest way is to create helper classes and put an instance into the model.

public class MathHelper {
    public long round(double number) {
        return Math.round(number);
    }
}
model.put("math", new MathHelper());

Note: Helpers don't have their own namespace, so you have to be careful not to overwrite them with other variables.

p= math.round(1.44)

Model Defaults (Global Variables)

If you are using multiple templates, you might need default objects available in all renders. Use globalVariables in RenderContext:

Map<String, Object> globals = new HashMap<>();
globals.put("city", "Bremen");
globals.put("country", "Germany");
globals.put("url", new MyUrlHelper());

RenderContext context = RenderContext.builder()
    .globalVariables(globals)
    .build();

// These variables are now available in every render using this context
String html = engine.render(template, model, context);

Java Records Support

Since version 3.0.0, pug4j supports Java records as model objects. Records are automatically wrapped to make their components accessible in templates using property syntax, just like with Maps or POJOs.

Example:

// Define records
record Author(String name, String email) {}
record Book(String title, double price, boolean available, Author author) {}

// Create model with records
Author author = new Author("Douglas Adams", "douglas@example.com");
Book book = new Book("The Hitchhiker's Guide to the Galaxy", 5.70, true, author);

Map<String, Object> model = new HashMap<>();
model.put("book", book);

Template usage:

div
  h1= book.title
  p Price: #{book.price} €
  if book.available
    p In stock!
  p Author: #{book.author.name} (#{book.author.email})

Key features:

Requirements:

Template Loader

By default, pug4j searches for template files in your work directory. By specifying your own FileTemplateLoader, you can alter that behavior. You can also implement the TemplateLoader interface to create your own.

TemplateLoader loader = new FileTemplateLoader("/templates/", "UTF-8");
loader.setBase("my-maintemplates/");

PugEngine engine = PugEngine.builder()
    .templateLoader(loader)
    .build();

Available loaders:

You can also implement the TemplateLoader interface to create your own custom loader.

Expressions

The original pug implementation uses JavaScript for expression handling in if, unless, for, case commands, like this

- var book = {"price": 4.99, "title": "The Book"}
if book.price < 5.50 && !book.soldOut
  p.sale special offer: #{book.title}

each author in ["artur", "stefan", "michael","christoph"]
  h2= author

Jexl Expressionhandler (default)

Pug4j uses JEXL for parsing and executing these expressions. JEXL syntax and behavior is very similar to ECMAScript/JavaScript and so closer to the original pug.js implementation. JEXL runs also much faster than GraalVM. If your template don't relies too much on Javascript-Logic and gets almost everything from the model, this is a good choice.

We are using a slightly modified JEXL version which to have better control of the exception handling. JEXL now runs in a semi-strict mode, where non existing values and properties silently evaluate to null/false where as invalid method calls lead to a PugCompilerException.

Reserved Words

JEXL comes with the three builtin functions new, size and empty. For properties with this name the . notation does not work, but you can access them with [].

- var book = {size: 540}
book.size // does not work
book["size"] // works

You can read more about this in the JEXL documentation.

GraalVM Expressionhandler (since 2.0.0 / experimental!)

If you want to use pure JavaScript expression handling, you can use the GraalJS Expression Handler. It supports native JavaScript expressions but is significantly slower than the JEXL Expression Handler. Configure it when building your engine:

PugEngine engine = PugEngine.builder()
    .expressionHandler(new GraalJsExpressionHandler())
    .build();

Framework Integrations

Breaking Changes in 3.0.0

API Redesign

Other Breaking Changes

New Features

Breaking Changes in 2.0.0

Breaking Changes in 1.3.1

Breaking Changes in 1.3.0

Breaking Changes in 1.2.0

Breaking Changes in 1.0.0

In Version 1.0.0 we added a lot of features of JadeJs 1.11. There are also some Breaking Changes:

Authors

Special thanks to TJ Holowaychuk the creator of jade!

License

The MIT License

Copyright (C) 2011-2025 neuland Büro für Informatik, Bremen, Germany

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Join libs.tech

...and unlock some superpowers

GitHub

We won't share your data with anyone else.