Apache Velocity A Java Template Engine Nathan Bubna
Apache Velocity A Java Template Engine Nathan Bubna nbubna@apache. org, Henning P. Schmiedehausen hps@intermeta. de OSCON 2007, July 25 th 2007 Portland, Oregon http: //people. apache. org/~nbubna/oscon 2007
Template Engine? • Defines a simple language (VTL – Velocity Template Language) • Templates are text containing active elements • Active elements are replaced with values from the model • No “industry standard” template language • Templates are processed, not compiled
Velocity Background - Velocity was started in 2000 - One of the first Jakarta projects - ASF-licensed alternative to Web. Macro - Language syntax is similar and still very stable - 100% Pure Java (runs on Java 1. 3 or better) - Velocity became an Apache TLP in 2006 - Current release is 1. 5 (as of March ’ 07)
Velocity Spotting - Velocity is integrated with many other projects (Turbine, Struts 2, Maven…) and others (http: //wiki. apache. org/velocity/Powered. By. Velocity) - Support for IDEs and Editors available (e. g. Eclipse, Intelli. J IDEA, emacs…) (http: //wiki. apache. org/velocity/Velocity. Editors) - Response content in webapp frameworks (e. g. Struts, Turbine) - Code generation (e. g. Torque, My. Eclipse) - Documentation (e. g. Maven, Anakia) - Email (e. g. Spring)
Velocity vs JSP - Easier to test - No servlet container required - Better separation of code and design - No compilation into Java code - Few, easy to learn language elements - No embedded Java code! - Easy on the eyes
Real Template Engines - perl: HTML-Template, Mason - php: Smarty, Smart. Template, Tiny. But. Strong - Ruby: Galena, Liquid. Ruby - Python: Quick. Silver, Cheetah, Turbo. Gears, Airspeed - Java: Web. Macro, Free. Marker, Apache Velocity
Velocity Template Language - Simple constructs - #directive() (line directives) - #directive() … #end (block directives) - $reference or ${reference} - Embedded directly into template files (no open / close tags like JSP or PHP) - References are “loosely typed” - VTL can be learned in minutes
Assignments - #set() - #set is used to create or update a reference - #set( $foo = “text” ) String value - #set( $foo = 100 ) Numeric value - #set( $foo = [ 1, 2, 3 ] ) Array - #set( $foo = { 1 : 2, 3 : 4 } ) Map - #set( $foo = $bar ) Reference - #set( $foo = $bar. foo ) Bean Property - #set( $foo = $bar. do. Foo() ) Method Result
Demo #1 - References - #set( $message = ’Hello World’ ) - This is a Velocity “$message” program. - #set( $favorite = 137 ) - My favorite number is not $favorite.
Display Control Elements - Loop - #foreach( $foo in $bars ). . . #end - Conditional - #if ( ) … #else … #end - Inclusion of external elements - #include( ) Load external file - #parse( ) Load and parse file
Demo #2 - Loops - #set( $list = [ ‘a’, ‘b’, ‘c’, ‘d’ ] ) - #foreach( $alpha in $list ) - The current letter is $alpha - #end - Let’s count #foreach( $i in [ 1. . 10 ] )$i #end
Demo #3 - Conditionals - #if( $speaker eq ‘Henning’ )##Use german - Hallo Welt! - #elseif( $hello ) - $hello - #else #*Use default greeting*# - Hi World! - #end
Macros - Builds a block directive on the fly - Create: #macro (name) … #end - Use: #name() … #end - Velocity supports global and local scope - Technically some sort of “method call” (please don’t use it like this) - For factoring out common template code/content
Macros - Macros can take parameters - Create: - #macro( name $arg 2 ) …$arg 2…#end - Use: - #name( $foo $bar ) … #end - Arbitrary number of parameters possible - Number of call parameters must match definition!
Demo #4 - Macros - #macro( quote $value )"$value"#end - We use a macro to quote #quote( 'this phrase' ).
Reference Syntax & Evaluation - A $reference represents a Java object - Use a${formal. Reference}to avoid parsing ambiguities - $!ref or $!{ref} means “be quiet when null” (do not confuse with !$reference) - Evaluation always invokes to. String()method
Velocity Miscellany - A range operator exists - #set ($foo = [ 1. . 100 ]) List of integers 1 to 100 - Arithmetic (both integer and floating point) - #set ($foo = 1. 5 + 2 ) $foo is now 3. 5 - +, -, /, *, % - Boolean operators for conditionals - !, &&, ||, ==, <, >, >= - not, and, or, eq, ne, gt, ge, lt, le - For == and !=, if the operands are not of the same class, their to. String() values are compared - String interpolation for #set(), macro args and method args - #set( $foo = “foo was $foo” ) $foo is now “foo was 3. 5”
Velocity Context - The Context is the means of importing values into the template - It is essentially a map of reference identifiers (i. e. the “foo” in ${foo}) to Java objects - All access to data in the template comes this way - There is no “natural” or “native” way to access or create Java objects
Demo – Using A Context - public static void main(String [] args) throws Exception { - Velocity. Engine engine = new Velocity. Engine(); - Velocity. Context context = new Velocity. Context(); - context. put(“speaker", “Nathan”); - context. put("hello", "Hello World!"); - Template template = engine. get. Template(args[0]); - String. Writer out = new String. Writer(); - template. merge(context, out); - System. out. println(out. to. String()); - }
Interacting With Context Objects - The real power of Velocity - All public methods in public classes are available - All works via runtime reflection - Shortcut notation for property access ($a. b vs $a. get. B()) - Type promotion as Java does - Method parameters can not be omitted! (this is not perl!)
Velocity. Tools - A “tool” is just a context object that is “useful” in a template - Collection of useful Java classes. - Comes in three flavors: - Generic. Tools All-purpose tools - Velocity. View Tools and more for webapps - Velocity. Struts Velocity as Struts View layer - Other “tools” out there on the web
Velocity. View - Velocity. View. Servlet renders arbitrary Templates through web. xml mapping - Configuration of tools with an XML based configuration file - Different tool scopes/lifecycles possible (application, session, request) - Request, Session, Response and Servlet. Context objects and their attributes are available automatically
Advanced Velocity - Custom directives possible (org. apache. velocity. runtime. directive. Directive) - Multiple Resource loaders to load templates from different sources (files, classpath, jars, database, remote URLs) - Event Handlers for Exception handling, XML escaping, etc - Custom Introspector for method and property access possible
Advanced Velocity - Velocity Template Language (VTL) is defined in Java. CC grammar - VTL itself can be changed or extended (needs recompilation of velocity. jar) - More “Advanced Velocity“ at http: //wiki. apache. org/velocity/Hacking. Velocity including the excellent Apache. Con 2004 session slides by Will Glass. Husain
Demo #5 - Velocity. View - Uses Velocity. Tools 2. 0 (only alpha release available) - Velocity. View. Servlet does the work - Uses Link. Tool, Parameter. Tool, Escape. Tool - (aka $link, $params, and $esc) - One custom tool: Address. Book is a ~30 line POJO - One template: index. vm is just ~50 lines - ~20 lines of config (including web. xml)
Velocity with Struts 1. x - Velocity. Tools provides Struts tools for integration - Seamless, not mutually exclusive with JSP - - (Image from http: //velocity. apache. org/tools/devel/struts/!)
Velocity with Struts 1. x - Action. Messages. Tool - Action Messages - Errors. Tool - Error Messages - Form. Tool - Forms handling - Message. Tool - i 18 n Message Support - Struts. Link. Tool, Secure. Link. Tool - Links - Tiles. Tool - Struts-Tiles Framework - Validator. Tool - Validator Framework
Velocity with Turbine - Preferred View Layer of Turbine - No separate Servlet - Turbine fully integrates Velocity - Turbine provides infrastructure - Tools - Template Loaders - Configuration and Logging
Velocity with… - Velocity is supported as a first-class view layer in - Struts 2. x (uses custom directives instead of tools) - Spring MVC (also supports Velocity. Tools 1. x well) - Click (http: //click. sourceforge. net/) - Restlet (http: //www. restlet. org/) - Mentawai (http: //www. mentaframework. org/) - And at least a dozen others… - (http: //wiki. apache. org/velocity/Powered. By. Velocity)
Other Velocity Uses - Texen for generic text generation - Anakia for XML to documentation - Torque – generate Java and SQL code - Velocity. View. Tag – Easily embed Velocity in JSP - (Part of the upcoming Velocity. Tools 2. 0) - Velosurf – Tool for abstracting database interaction
Any questions?
Where to go from here? - Velocity Homepage - http: //velocity. apache. org/ - Velocity Mailing Lists - http: //velocity. apache. org/contact. html - Velocity Wiki - http: //wiki. apache. org/velocity/ - These Slides and Demo Code - http: //people. apache. org/~nbubna/oscon 2007 - Velocity 1. 5 Release Notes - http: //wiki. apache. org/jakarta-velocity/Velocity 15 Release. Notes
Thanks for your attention!
- Slides: 33