Open Source Series 2.: NVelocity

Formerly as part of the Apache Jakarta project, now part of the Apache project itself can be found the Velocity project. Since the beginning, it is the de facto tool for generating template driven applications – websites, documents, etc., the list of projects, websites and tools powered by or capable of using Velocity is endless. As for other great and successfull projects (like Hibernate, which also uses velocity for generating POJO files), this was met with the new wind of .NET – there were NVelocity born. So to make it short – NVelocity is a .Net-based template engine – it permits anyone to use the simple yet powerful template language called VTL to reference objects, execute methods, etc defined in .Net code. Speaking of a web application, this leads to the MVC pattern – this simple to use and set up tool enables you to program against modells in your views, and put the controller in charge of binding the two – this (and NHibernate, and ActiveRecord, and Windsor…) is what lead to the born of the Castle and the Rhino projects – but these are in later post :).

So no whistles nor bells, but the main part of NVelocity is:

  • You create the engine – new NVelocity.App.VelocityEngine(ep);
  • You get a template – engine.GetTemplate(“template.vm”);
  • You create a context – new NVelocity.VelocityContext();
  • You fill the context – context.Put(“key”, “value”);
  • Than you merge the context with the template using the engine – template.Merge(context, outputStream);

The extras are coming mostly in the template file, and by the fact, that there are plenty of way to provide plugins into the system – ResourceLoaders for determining where to get the file (from the filesystem? database? embedded resource?), caches of various parts, etc. So, back to template file – what can I do?

  • I can print the value for a key – ${key}
  • I can use property getters and setters – #set ${object}.prop = “value”
  • I can use loops, if-then-else, define macros, etc
  • Call and return any method with parameterlists which may contain values, arrays, dictionaries, etc – ${object}.Method(${key}, “%{key = ‘value’, key2 = ${key}}”);
  • Meanwhile the whole thing is typesafe and – the template gets compiled into an AST tree the first time it met!

So – I think this is a very handy tool for generating source files, for generating documents and for driving data driven websites.

PS: No, it has nothing to do with Microsoft Velocity – that goes into the cache providers series 🙂

This post is part of the open source series

Leave a Reply

Your email address will not be published. Required fields are marked *