Apache Velocity A Java Template Engine <ul><li>Nathan Bubna </li></ul><ul><li>[email_address] , </li></ul><ul><li>Henning ...
Template Engine? <ul><li>Defines a simple language (VTL – Velocity Template Language) </li></ul><ul><li>Templates are text...
Velocity Background <ul><li>Velocity was started in 2000 </li></ul><ul><li>One of the first Jakarta projects </li></ul><ul...
Velocity Spotting <ul><li>Velocity is integrated with many other projects (Turbine, Struts 2, Maven…) and others  ( http:/...
Velocity vs JSP <ul><li>Easier to test </li></ul><ul><li>No servlet container required </li></ul><ul><li>Better separation...
Real Template Engines <ul><li>perl:  HTML-Template, Mason </li></ul><ul><li>php:  Smarty, SmartTemplate,  TinyButStrong </...
Velocity Template Language <ul><li>Simple constructs </li></ul><ul><ul><li># directive()  (line directives) </li></ul></ul...
Assignments - #set() <ul><li>#set is used to create or update a reference </li></ul><ul><ul><li>#set( $foo = “text” )  Str...
Demo #1 - References <ul><li>#set( $message = ’Hello World’ ) </li></ul><ul><li>This is a Velocity “$message” program. </l...
Display Control Elements <ul><li>Loop </li></ul><ul><ul><li>#foreach( $foo in $bars ) ... #end </li></ul></ul><ul><li>Cond...
Demo #2 - Loops <ul><li>#set( $list =  [  ‘ a ’ ,  ‘ b ’ ,  ‘ c ’ ,  ‘ d ’  ]  ) </li></ul><ul><li>#foreach(   $ alpha  in...
Demo #3 - Conditionals <ul><li>#if( $speaker eq ‘Henning’ )##Use german </li></ul><ul><li>  Hallo Welt! </li></ul><ul><li>...
Macros <ul><li>Builds a block directive on the fly </li></ul><ul><ul><li>Create:  #macro (name) … #end </li></ul></ul><ul>...
Macros <ul><li>Macros can take parameters </li></ul><ul><ul><li>Create:  </li></ul></ul><ul><ul><ul><li>#macro( name $arg ...
Demo #4 - Macros <ul><li>#macro( quote $value )&quot;$value&quot;#end </li></ul><ul><li>We use a macro to quote #quote( 't...
Reference Syntax & Evaluation <ul><li>A  $ reference  represents a Java object </li></ul><ul><li>Use a${ formalReference }...
Velocity Miscellany <ul><li>A range operator exists </li></ul><ul><ul><li>#set ($foo = [ 1..100 ]) List of integers 1 to 1...
Velocity Context <ul><li>The Context is the means of importing values into the template </li></ul><ul><li>It is essentiall...
Demo – Using A Context <ul><li>public static void main(String [] args) throws Exception { </li></ul><ul><li>VelocityEngine...
Interacting With Context Objects <ul><li>The real power of Velocity </li></ul><ul><li>All public methods in public classes...
VelocityTools <ul><li>A “tool” is just a context object that is “useful”  in a template </li></ul><ul><li>Collection of us...
VelocityView <ul><li>VelocityViewServlet renders arbitrary Templates through web.xml mapping </li></ul><ul><li>Configurati...
Advanced Velocity <ul><li>Custom directives possible  (org.apache.velocity.runtime.directive.Directive) </li></ul><ul><li>...
Advanced Velocity <ul><li>Velocity Template Language (VTL) is defined in JavaCC grammar </li></ul><ul><li>VTL itself can b...
Demo #5 - VelocityView <ul><li>Uses VelocityTools 2.0 (only alpha release available) </li></ul><ul><li>VelocityViewServlet...
Velocity with Struts 1.x <ul><li>VelocityTools provides Struts tools for integration </li></ul><ul><li>Seamless, not mutua...
Velocity with Struts 1.x <ul><ul><li>ActionMessagesTool - Action Messages </li></ul></ul><ul><ul><li>ErrorsTool - Error Me...
Velocity with Turbine <ul><li>Preferred View Layer of Turbine </li></ul><ul><li>No separate Servlet </li></ul><ul><li>Turb...
Velocity with… <ul><li>Velocity is supported as a first-class view layer in </li></ul><ul><ul><li>Struts 2.x (uses custom ...
Other Velocity Uses <ul><li>Texen  for generic text generation </li></ul><ul><li>Anakia  for XML to documentation </li></u...
Any questions?
Where to go from here? <ul><li>Velocity Homepage </li></ul><ul><ul><li>http://velocity.apache.org/ </li></ul></ul><ul><li>...
Thanks for your attention!
Upcoming SlideShare
Loading in...5
×

Apache Velocity

994

Published on

Apache Velocity Small Notes

Published in: Education, Technology, Business
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
994
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
17
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide
  • Apache Velocity

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

      Clipping is a handy way to collect important slides you want to go back to later.

    ×