• Stars
    star
    1,817
  • Rank 25,437 (Top 0.6 %)
  • Language
    HTML
  • License
    Other
  • Created over 14 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Implementation of mustache.js for Java

Mustache.java Build Status FOSSA Status

Mustache.java is not designed to allow untrusted parties to provide templates. It may be possible to lock it down to provide that safely, but by default it is UNSAFE. Use the SafeMustacheFactory and whitelist all templates and partials.

As of release 0.9.0 mustache.java is now Java 8 only. For Java 6/7 support use 0.8.x.

There are no external dependencies and the compiler library is ~100k.

Mustache.java is a derivative of mustache.js.

There is a Google Group for support and questions: http://groups.google.com/group/mustachejava

Travis CI: https://travis-ci.org/spullara/mustache.java

API documentation: http://spullara.github.io/mustache/apidocs/

Largest production deployment of Mustache.java:

  • Twitter (the web site, email, syndicated widgets, etc)

Thanks to YourKit for many performance improvements:

YourKit is kindly supporting the mustache.java open source project with its full-featured Java Profiler. YourKit, LLC is the creator of innovative and intelligent tools for profiling Java and .NET applications. Take a look at YourKit's leading software products:

Request for contributions:

  • Real world benchmarks that matter - currently benchmarking based on Twitter templates
  • Documentation
  • Bug reports / fixes
  • API feedback
  • Optimizations

Documentation:

  • Javadocs
  • Mustache.js manual
  • Passes all of the mustache specification tests modulo whitespace differences
  • Biggest difference between mustache.js and mustache.java is optional concurrent evaluation
  • Data is provided by objects in an array of scopes and are accessed via non-private fields, methods or maps
  • Any Iterable can be used for list-like behaviors
  • Returning a Callable allows for concurrent evaluation if an ExecutorService is configured
  • Template inheritance is supported by this implementation, see mustache/spec#38 (eg. {{<super}}{{$content}}...{{/content}}{{/super}})
  • Additional functions/lambdas (eg. {{#func1}}...{{/func1}}) are implemented using Function from Java 8 (post-substitution)
  • Use TemplateFunction if you want mustache.java to reparse the results of your function/lambda (pre-substitution)
  • Both default and manually configured classpath based and file system based template roots are supported
  • A compiled and invokedynamic version is available. Performance improvements are often application specific.
  • The handlebar server will render templates + json data for quick mockups of templates by designers
  • Completely pluggable system for overriding almost all the behavior in the compilation and rendering process
  • You can pull out sample data from live systems using the CapturingMustacheVisitor for mocks and tests
  • The DecoratedCollection can provide first / last / index for elements in a collection
  • The invert call can take text and a template and solve for the data

Performance:

  • See the com.github.mustachejavabenchmarks package in the compiler module
  • Compiles 4000+ timeline.html templates per second per core
  • Renders 3000+ of 50 tweet timelines per second per core on 2011 Macbook Pro / MacPro hardware
  • New codegen module generates code for guards and mustaches
  • The indy module uses the codegen module and invokedynamic to compile templates down to bytecode

Build suggestions:

  • Don't build, use Maven dependencies
  • If you must build but not test:
  • If you must build and test but not benchmark:
    • CI=1 mvn clean install -pl :compiler -am
  • If you must build, test and benchmark:
    • mvn clean install

Maven dependency information (ie. for most common cases you will just need the compiler module):

Java 8+:

<dependency>
  <groupId>com.github.spullara.mustache.java</groupId>
  <artifactId>compiler</artifactId>
  <version>0.9.10</version>
</dependency>

Java 6/7:

<dependency>
  <groupId>com.github.spullara.mustache.java</groupId>
  <artifactId>compiler</artifactId>
  <version>0.8.18</version>
</dependency>

Example template file:

{{#items}}
Name: {{name}}
Price: {{price}}
  {{#features}}
  Feature: {{description}}
  {{/features}}
{{/items}}

Might be powered by some backing code:

public class Context {
  List<Item> items() {
    return Arrays.asList(
      new Item("Item 1", "$19.99", Arrays.asList(new Feature("New!"), new Feature("Awesome!"))),
      new Item("Item 2", "$29.99", Arrays.asList(new Feature("Old."), new Feature("Ugly.")))
    );
  }

  static class Item {
    Item(String name, String price, List<Feature> features) {
      this.name = name;
      this.price = price;
      this.features = features;
    }
    String name, price;
    List<Feature> features;
  }

  static class Feature {
    Feature(String description) {
       this.description = description;
    }
    String description;
  }
}

And would result in:

Name: Item 1
Price: $19.99
  Feature: New!
  Feature: Awesome!
Name: Item 2
Price: $29.99
  Feature: Old.
  Feature: Ugly.

Evaluation of the template proceeds serially. For instance, if you have blocking code within one of your callbacks, the system will pause while executing them:

static class Feature {
  Feature(String description) {
    this.description = description;
  }

  String description() throws InterruptedException {
    Thread.sleep(1000);
    return description;
  }
}

If you change description to return a Callable instead it will automatically be executed in a separate thread if you have provided an ExecutorService when you created your MustacheFactory.

Callable<String> description() throws InterruptedException {
  return new Callable<String>() {

    @Override
    public String call() throws Exception {
      Thread.sleep(1000);
      return description;
    }
  };
}

This enables scheduled tasks, streaming behavior and asynchronous i/o. Check out the example module in order to see a complete end-to-end example:

package mustachejava;

import com.github.mustachejava.DefaultMustacheFactory;
import com.github.mustachejava.Mustache;
import com.github.mustachejava.MustacheFactory;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.Arrays;
import java.util.List;

public class Example {

  List<Item> items() {
    return Arrays.asList(
      new Item("Item 1", "$19.99", Arrays.asList(new Feature("New!"), new Feature("Awesome!"))),
      new Item("Item 2", "$29.99", Arrays.asList(new Feature("Old."), new Feature("Ugly.")))
    );
  }

  static class Item {
    Item(String name, String price, List<Feature> features) {
      this.name = name;
      this.price = price;
      this.features = features;
    }

    String name, price;
    List<Feature> features;
  }

  static class Feature {
    Feature(String description) {
      this.description = description;
    }

    String description;
  }

  public static void main(String[] args) throws IOException {
    MustacheFactory mf = new DefaultMustacheFactory();
    Mustache mustache = mf.compile("template.mustache");
    mustache.execute(new PrintWriter(System.out), new Example()).flush();
  }
}

An alternative approach for providing variables would be to use a Map object, like:

  public static void main(String[] args) throws IOException {
    HashMap<String, Object> scopes = new HashMap<String, Object>();
    scopes.put("name", "Mustache");
    scopes.put("feature", new Feature("Perfect!"));

    Writer writer = new OutputStreamWriter(System.out);
    MustacheFactory mf = new DefaultMustacheFactory();
    Mustache mustache = mf.compile(new StringReader("{{name}}, {{feature.description}}!"), "example");
    mustache.execute(writer, scopes);
    writer.flush();
  }

License

FOSSA Status

More Repositories

1

redis-protocol

Java client and server implementation of Redis
Java
351
star
2

cli-parser

Parse CLI command lines
Java
102
star
3

havrobase

Use Avro to store all your values in HBase instead of regular columns
Java
74
star
4

nbd

NDB server
Java
57
star
5

browsercrawler

Crawl websites from your browser and save them in S3
JavaScript
55
star
6

interviewcode

At Twitter I often asked a simple question, render a tweet given the text and an unordered list of its entities
Java
39
star
7

mysql-connector-java

Import of the mysql jdbc connector for optimization purposes
Java
27
star
8

findmyiphone

Find your iPhone by scraping the MobileMe site and turning it into a simple REST API
Java
21
star
9

java-future-jdk8

Java Future proposal for JDK8
Java
19
star
10

gpt-j-6b

Dockerfile and web server for running GPT-J-6B on AWS GPU instances
Python
18
star
11

teslalogger

Logs your vehicle information to a file
Java
15
star
12

onvif

Java client for onvif based IP cameras
Java
12
star
13

oauth

Fork of the OAuth Core library
Java
9
star
14

YQL-Storage-Editor

The YQL Storage Editor is an HTML/CSS/JS editor for content stored in yql.storage.
JavaScript
7
star
15

tikvclient

Java client for TiKV by Pingcap
Java
7
star
16

corpuscompression

Achieve better compression for small objects with a predefined corpus
Java
7
star
17

twickery

Push your Twitter activity (favorites, tweets, photos, follows, profile updates) to Facebook ticker
Java
7
star
18

avrocompiler

Alternative template based Avro compiler
Java
6
star
19

mustachelet

Servlet for serving Mustache based templates with backing Java code
Java
5
star
20

scala-plugin

fork of the idea scala plugin
Scala
4
star
21

urlmonitor

Monitors a URL and sends an email when it is down
Java
4
star
22

bfes

Brute force embedding search
Rust
3
star
23

lambdabenchmark

Benchmarking AWS Lambda invocations
Java
3
star
24

photoindex

OpenCLIP photo index and search application
Python
3
star
25

thepusher

Pushes values into your objects. Resistance is futile.
Java
3
star
26

mojava

More Java classes for convenience. Not huge frameworks. Just generically useful stuff.
Java
3
star
27

firebrowser

Update FireEagle using HTML5
Java
3
star
28

codegraph

Load jars into Neo4J and search them
Java
3
star
29

mustache.rs

Port of mustache.java to Rust
Rust
3
star
30

jstacker

Process Jstacks results and compare them across runs
Scala
2
star
31

buffertest

Bytes vs ChannelBuffer vs ByteBuf
Java
2
star
32

cleanuptheweb

Safari extension that replaces bad words with ****
JavaScript
2
star
33

spullara.github.com

Sam Pullara's Site
HTML
2
star
34

mqtt

Java/FDB based version of an MQTT 3.1.1 compatible server
Java
2
star
35

jorstache

Jornado & mustache.java integration project
Java
2
star
36

mustache.scala

Mustache for Scala built to be used with Twitter Scala libraries
Scala
2
star
37

redispatterns

Various patterns for using Redis implemented in Java
2
star
38

simpleconfig

Simple configuration management for applications using simpledb
Java
2
star
39

jlink-custom-runtimes

AWS Lambda custom runtime that supports Java 9, 10, 11, 12, etc. via jlink
Java
2
star
40

vals

Implement vals and lazy vals using a java agent
Java
1
star
41

maptool

Java
1
star
42

locrest

Automatically exported from code.google.com/p/locrest
Java
1
star
43

bootstraplet

Build bootstrap based projects integrated with mustache using extensions
1
star
44

echo

Echo servers
1
star
45

dropboxs3sync

Syncs a dropbox folder to an S3 bucket
JavaScript
1
star
46

avro-generated-code

Example of why the current generated code isn't any good
1
star
47

pokerengine

A reasonable but not great poker engine
Java
1
star
48

json2csv

Really simple converter from JSON to CSV format
Java
1
star
49

s3benchmark

Just some simple benchmarking for how fast you can write and read from S3
Java
1
star
50

guessyournumber

Kids game
1
star
51

jaxrsprotobuf

Example code for one my most popular blog posts from the distant past.
C++
1
star
52

consolidateddb

1
star
53

rumble

1
star
54

spellcheck

Peter Norvig's spellchecker in Java 8 streams
Java
1
star
55

2ldr

tl;dr url shortener
1
star
56

unshredder

1
star
57

fdb

Various FoundationDB utilities and data structures
Java
1
star
58

jets3t

S3 access library
1
star
59

timeflow

Analyze system-wide expected performance
1
star
60

thefeed

The Feed
Java
1
star
61

pattern

Some fixes for the OpenJDK 6/7 Pattern class
Java
1
star
62

scala-parent-pom

Scala 2.8.1 project parent pom
1
star
63

streaming

Just some experiments to understand JDK8 better
1
star
64

twittermarkovgenerator

Reads tweets from a users timeline and generates "sentences" based on the word cooccurence and distribution
Java
1
star
65

webtroller

Control web pages with natural language
JavaScript
1
star