MVEL Templating Introduction

Posted 2009-01-29 in Java by Johann.

MVEL is an expression language – similar to OGNL – and a templating engine.

I’d like to give you an example of MVEL Templates in this post so you can find out if MVEL might work for you.

Templating Examples

This is how templating with MVEL looks like.

Basic Object Access

<h1>@{name}</h1>

Simple Iteration

<p>
@foreach{index : alphabetical}
<a href="@{index.uri}">@{index.description}</a>
@end{}
</p>

Accessing Static Methods

<a href="@{ua.pageURI}">
@{org.apache.commons.lang.StringEscapeUtils.escapeHtml(ua.name)}
</a>

Inline Ternary Operator

<li>
@{ua.hitsTotal} total @{ua.hitsTotal == 1 ? "Hit" : "Hits"}.
</li>

MVEL Integration

The following code integrates MVEL into your application. The first part parses a template from a String, the second part applies an object to the template and writes it to a file.

public class MVELTemplateWriter {

    private final CompiledTemplate template;

    /**
     * Constructor for MVELTemplateWriter.
     *
     * @param template the MVEL template
     */
    public MVELTemplateWriter(String template) {
        super();
        this.template = TemplateCompiler.compileTemplate(template);
    }

    /**
     * Merge an Object with the template and write the output
     * to f.
     *
     * @param o the Object
     * @param f the output File
     */
    public void write(Object o, File f) throws IOException {
        String output = (String)
            TemplateRuntime.execute(template, o);
        Writer writer = null;
        try {
            if (!f.getParentFile().exists()) {
                boolean created = f.getParentFile().mkdirs();
                assert created;
            }
            writer = new OutputStreamWriter(new
                FileOutputStream(f), "UTF-8");
            writer.write(output);
        }
        finally {
            close(writer);
        }
    }

}

You use this code like you would use other templating engines/expression languages: You add your objects to a Map and then merge the Map with a template. In the template, you reference the objects in the Map by their key.

Note that the template is pre-compiled for performance reasons. You can use something like FileUtils.readFileToString(File) to read a template file into a String.

Summary

Good

I liked:

  • Speed is excellent. Most of the time when building the User Agent Database is spent writing graphs and parsing log files however.
  • Clean syntax. Cleaner than everything Sun has ever produced, but probably not as clean and simple as Velocity.
  • Supports arbitrary methods. Velocity makes it hard to use static methods and does not support operations on arrays at all.

Bad

Not all is nice however. I did not like the following:

  • No streaming output. All output is cached in RAM before it can be written to a file.

Do you use a templating engine/expression language? Maybe you use Velocity, OGNL, FreeMaker, StringTemplate or something else entirely? Please post a comment if you do.

9 comments

#1 2009-01-30 by Mike Brock

You should post a JIRA about the lack of streaming output. It's a good observation, and there's no reason why it should not be able to accommodate that use case.

I see no reason why an abstraction cannot be added to the way it appends to output to direct it to an OutputStream instead.

BTW, Would you be okay with me linking to this blog entry as an "External Tutorial" for templates?

#2 2009-01-30 by Johann

Mike,

ok, I'll post an issue. And yes, you can definitely link to this page. Any page, even :-)

#3 2009-01-30 by Mike Brock

Johann,

Cool. I've linked this article from the MVEL templates documentation page. I'll definitely look into adding support for streaming output.

#4 2009-01-31 by Johann

Thanks Mike!

#5 2009-01-31 by Brad

Another copy of Velocity / Freemarker? Oh please.

#6 2009-05-06 by Ransford

Hi,
I am new to to teemplating and I wnt to know which ext do i use to read an html file to parse the template, it template1.mvel or template1.html

#7 2009-05-06 by Johann

Ransford,

it doesn't matter at all since you have to read the template yourself anyway. MVEL doesn't have any automatic processing of folders or files, I think.

#8 2009-05-14 by Mike Brock

By the way, there is no streaming output support in the latest versions of MVEL. http://jira.codehaus.org/browse/MVEL-136

#9 2009-05-14 by Mike Brock

I mean there is NOW streaming output support :)

Subscribe

RSS 2.0, Atom or subscribe by Email.

Top Posts

  1. DynaCloud - a dynamic JavaScript tag/keyword cloud with jQuery
  2. 6 fast jQuery Tips: More basic Snippets
  3. xslt.js version 3.2 released
  4. xslt.js version 3.0 released XML XSLT now with jQuery plugin
  5. Forum Scanners - prevent forum abuse
  6. Automate JavaScript compression with YUI Compressor and /packer/

Navigation