Kinder Surprise - three wishes at once!

Templates are a very simple way to structure your code. With them you basically add html snippets as a script tag to your dom. Then you can reference them which creates much cleaner code.

Here’s an example from the knockout documentation:

<h2>Participants</h2>
Here are the participants:
<div data-bind="template: { name: 'person-template', data: buyer }"></div>
<div data-bind="template: { name: 'person-template', data: seller }"></div>
 
<script type="text/html" id="person-template">
    <h3 data-bind="text: name"></h3>
    <p>Credits: <span data-bind="text: credits"></span></p>
</script>

But adding them to your html in a script tag has some drawbacks. First we’d like to minimize the size of your html. Second, we’re missing syntax highlighting in the IDE. And third, wouldn’t it be great if it was lazy loaded?

“But darling that’s three wishes altogether! You know that’s not possible!”

“But yes, it is possible!” Just use this little snippet:

public class KinderSurprise {

    static String convertStreamToString(java.io.InputStream is) {
        java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
        return s.hasNext() ? s.next() : "";
    }

    public static void load(String name, InputStream template) {
        load(name, convertStreamToString(template));
    }

    /**
     * Register script tag in DOM element of index.html
     *
     * @param name
     * @param template
     */
    @JavaScriptBody(args = {"name", "template"}, body = "console.log('try to register '+name);"
            + "var my_template = document.createElement('script');\n"
            + "my_template.setAttribute('id', name);\n"
            + "var newContent = document.createTextNode(template); \n"
            + "my_template.appendChild(newContent); "
            + "document.body.appendChild(my_template);\n")
    private static native void load(String name, String template);
}

With this little snippet you can load any template lazily:

KinderSurprise.load("template", MyViewModel.class.getResourceAsStream("template.html"));

The template itself is a regular html snippet, so any decent IDE will give you syntax highlighting and code completion. Your main html file is clean and small and the script is loaded lazily.

“KinderSurprise three wishes at once” - from DukeScript!

P.s.: This is just one (very simple) way of doing it. Stay tuned for more feature rich alternatives.