Apache Velocity 1.6

7,732
-1

Published on

Published in: Technology
2 Comments
14 Likes
Statistics
Notes
No Downloads
Views
Total Views
7,732
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
0
Comments
2
Likes
14
Embeds 0
No embeds

No notes for slide
  • mvn exec:java -Dexec.mainClass=org.apache.velocity.contextdemo.ContextDemo -Dexec.args=src/main/templates/Test.vm
  • Apache Velocity 1.6

    1. 1. An Introduction to Apache Velocity 1.6 Henning Schmiedehausen henning@apache.org ApacheCon 2009, Oakland, CA, U.S.A.
    2. 2. Templating Engine? • Uses a simple language (Velocity Templating Language = VTL) • Templates are text which contains active elements • Active elements are replaced with values from the Model • No "industry standard" templating language • Templates are processed, not compiled
    3. 3. Templating engines • perl • HTML-Template, Mason • PHP • Smarty, SmartTemplate, TinyButStrong • Ruby • Galena, LiquidMarkup, ERB, lots more • Python • QuickSilver, Cheetah, TurboGears, Airspeed • Java • WebMacro, StringTemplate, FreeMarker, Apache Velocity ApacheCon US 2009
    4. 4. A short history of Velocity • Started in 2000 • One of the first Apache Jakarta projects • ASF-licensed alternative to WebMacro • Language syntax similar and very stable • 100% pure Java, runs on Java 1.3 or better • Apache TLP since 2006, from Jakarta • Current release: 1.6.2 (March '09) ApacheCon US 2009
    5. 5. Velocity Spotting • Velocity is integrated in many other Apache projects • Web Frameworks: Click, Wicket, Struts, Turbine • Other projects: Maven, Camel, Portals, Tiles http://wiki.apache.org/velocity/PoweredByVelocity • Support for IDEs and Editors available (e.g. Eclipse, IntelliJ, emacs...) http://wiki.apache.org/velocity/VelocityEditors • View Component in Web Frameworks • Code Generation (Apache Torque, Eclipse) • Documentation Generation (Maven, Anakia, Texen) • E-Mail Templating (e.g. Spring Framework) ApacheCon US 2009
    6. 6. 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! • better read- and understandable ApacheCon US 2009
    7. 7. Template Example <div>${addr.title} ${addr.first} ${addr.last}</div> <div>${addr.street}</div> <div>${addr.town} ${addr.zip}, ${addr.state}</div> <b>Invoice</b> <div>Date: $format.date(${time.currDate})</div> <table> <tr><th>Pos</th><th>Description</th><th>Price</th> <th>Qty</th><th>Total</th></tr> #foreach($item in $invoice.items) <tr><td>$velocityCount</td><td>$item.desc</td> <td>$format.money($item.price)</td><td>$item.quantity</td> <td>$format.money($item.total)</td></tr> #end </table> <div>Total $format.money($invoice.total)</div> <div>Tax $format.money($invoice.tax)</div> ApacheCon US 2009
    8. 8. Template Result Mr John Doe 1234 Evergreen Terrace Springfield, 12345, AY Invoice Date: Nov 3rd, 2009 Pos Description Price Qty Total 1 TV Set $499.95 1 $499.95 2 BluRay Player $299.95 1 $299.95 Various BluRay 3 $9.95 5 $49.95 Titles Total $849.97 Tax $49.90 ApacheCon US 2009
    9. 9. Template deciphered <div>${addr.title} ${addr.first} ${addr.last}</div> <div>${addr.street}</div> <div>${addr.town} ${addr.zip}, ${addr.state}</div> <b>Invoice</b> A "con $format.date(${time.currDate})</div> <div>Date:xt te o bject" contai <table> getter ns the s for t a he fiel ddress. It h <tr><th>Pos</th><th>Description</th><th>Price</th> getTit le(), g ds: as <th>Qty</th><th>Total</th></tr> etFirst #foreach($item n(), (), getLast(), getTo in $invoice.items) w getZip g (), get etStreet(), <tr><td>$velocityCount</td><td>$item.desc</td> State() <td>$format.money($item.price)</td><td>$item.quantity</td> <td>$format.money($item.total)</td></tr> #end </table> <div>Total $format.money($invoice.total)</div> <div>Tax $format.money($invoice.tax)</div> ApacheCon US 2009
    10. 10. Template deciphered A ${addr.last}</div> <div>${addr.title} ${addr.first} nother c forma ontex <div>${addr.street}</div> tters f t obje or dat ct con <div>${addr.town} ${addr.zip}, ${addr.state}</div>e and tains Such a curren n obje cy. <b>Invoice</b> ct is c alled a <div>Date: $format.date(${time.currDate})</div> "Tool" . <table> <tr><th>Pos</th><th>Description</th><th>Price</th> <th>Qty</th><th>Total</th></tr> #foreach($item in $invoice.items) <tr><td>$velocityCount</td><td>$item.desc</td> <td>$format.money($item.price)</td><td>$item.quantity</td> <td>$format.money($item.total)</td></tr> #end </table> <div>Total $format.money($invoice.total)</div> <div>Tax $format.money($invoice.tax)</div> ApacheCon US 2009
    11. 11. Template deciphered <div>${addr.title} ${addr.first} ${addr.last}</div> <div>${addr.street}</div> <div>${addr.town} ${addr.zip}, ${addr.state}</div> The "i n iterab voice" obje <b>Invoice</b> le field ct con loop c . The tains a #forea <div>Date: $format.date(${time.currDate})</div> reates n the ite ch...#e mized nd <table> list. <tr><th>Pos</th><th>Description</th><th>Price</th> <th>Qty</th><th>Total</th></tr> #foreach($item in $invoice.items) <tr><td>$velocityCount</td><td>$item.desc</td> Fun fa <td>$format.money($item.price)</td><td>$item.quantity</td> ct: Vel conve o nient city p <td>$format.money($item.total)</td></tr> rovid es a count #end for loo ps! </table> <div>Total $format.money($invoice.total)</div> <div>Tax $format.money($invoice.tax)</div> ApacheCon US 2009
    12. 12. Template deciphered <div>${addr.title} ${addr.first} ${addr.last}</div> <div>${addr.street}</div> Th ${addr.state}</div> <div>${addr.town} ${addr.zip}, e rema This c inder is just an be <b>Invoice</b> HTML any ki formatted t n <div>Date: $format.date(${time.currDate})</div> d of text , XML ext. or pla , in tex e.g. <table> t. <tr><th>Pos</th><th>Description</th><th>Price</th> <th>Qty</th><th>Total</th></tr> #foreach($item in $invoice.items) <tr><td>$velocityCount</td><td>$item.desc</td> <td>$format.money($item.price)</td><td>$item.quantity</td> <td>$format.money($item.total)</td></tr> #end </table> <div>Total $format.money($invoice.total)</div> <div>Tax $format.money($invoice.tax)</div> ApacheCon US 2009
    13. 13. Velocity Template Language • Simple Constructs • #directive() - line directives • #directive() ... #end - block directives • $reference or ${reference} - references • Embedded directly into template files (no open or close tags like php or JSP) • References are "loosely typed" ApacheCon US 2009
    14. 14. Assignments - #set() • #set creates or updates 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 getter • #set( $bar.foo = "200" ) Bean setter • #set( $foo = $bar.doFoo() ) Method Result ApacheCon US 2009
    15. 15. Demo #1 - References #set( $message = 'Hello World' ) This is a Velocity "$message" program. #set( $favorite = 137 ) My favorite number is not ${favorite}. ApacheCon US 2009
    16. 16. Control structures • Loop • #foreach( $foo in $bars ) ... #end • loops can be terminated with #break • $velocityCount provides loop count • $velocityHasNext allows "peeking ahead" • Conditional • #if ( ) … #elseif ( ) … #else … #end ApacheCon US 2009
    17. 17. Control structures • Inclusion of external elements • #include() Load external file • #parse() Load and parse file • Turn VTL blocks into references • #define(name) ... #end • Evaluate templates on the fly • #evaluate(...) ApacheCon US 2009
    18. 18. Demo #2 - Loops #set( $list = [ 'a ', ' b ', ' c ', ' d ' ] ) #foreach( $alpha in $list ) The current letter is ${alpha}. Hint: O pening #end a bloc k can and cl osing be on el the sa ement of me lin Let’s count: #foreach( $i in [ 1..10 ] )$i #end e! ApacheCon US 2009
    19. 19. Demo #3 - Conditionals #if( $lang eq "DE" ) ##Use german Hallo Welt! #elseif( $lang eq "FR" ) Bonjour Monde! #else #*Use default greeting*# Hello World! #end ApacheCon US 2009
    20. 20. Bonus Slide: Comment Syntax #if( $lang eq "DE" ) ##Use german Hallo Welt! #elseif( $lang eq "FR" ) Bonjour Monde! #else #*Use default greeting*# ThHello World! is is th e Velo city co ## com mmen ments #end to the t synta #* .... x: *# enc end of loses the lin a mult e, iline c omme nt. ApacheCon US 2009
    21. 21. Macros • Builds a block directive on the fly • Create: #macro (name) … #end • Use: #name() … #end • global and local scope supported • Technically some sort of “method call” (please don’t use it like this) • factor out common template code/content ApacheCon US 2009
    22. 22. Macros • Macros can take parameters • Create: #macro( name $arg1 $arg2 ) … $arg1 … $arg2 … #end • Use: #name( $foo $bar ) … #end • Arbitrary number of parameters possible • Number of call parameters must match definition! ApacheCon US 2009
    23. 23. Demo #4: Macros #macro( quote $value ) &quot;$value&quot; #end A macro quotes #quote( 'this phrase' )! Result: A macro quotes &quot;this phrase&quot;! ApacheCon US 2009
    24. 24. Reference Syntax & Evaluation • Any reference represents a Java object • Use ${reference} to avoid parsing ambiguities • If a reference resolves to "null", the reference itself is inserted in the template • $!ref or $!{ref} means "be quiet when null" • Evaluation uses toString() method ApacheCon US 2009
    25. 25. Reference Syntax & Evaluation • Any reference represents a Java object • Use ${reference} to avoid parsing ambiguities • If a reference resolves to "null", the Yeah, that w as a s reference itself is inserted in the template tupid idea. • $!ref or $!{ref} means "be quiet when null" • Evaluation uses toString() method ApacheCon US 2009
    26. 26. Reference Syntax & Evaluation • Any reference represents a Java object • Use ${reference} to avoid parsing ambiguities • If a reference resolves to "null", the reference itself is inserted in the template • $!ref or $!{ref} means "be quiet when null" • Evaluation uses toString() method ApacheCon US 2009
    27. 27. Reference Syntax & Evaluation • Any reference represents a Java object • Use ${reference} to avoid parsing Trivia: C an end onfusing $ less so !{foo} urce o with !$ ambiguities Also !$ !{foo} f fun! {foo} c an be and in lo credib oks awkwa • If a reference resolves to "null", the ly use ful. rd but is vali d VTL reference itself is inserted in the template • $!ref or $!{ref} means "be quiet when null" • Evaluation uses toString() method ApacheCon US 2009
    28. 28. Velocity Operators • Arithmetic operators • #set ($foo = 5 / 2 ) ## is 2! #set ($foo = 5.0 / 2) ## is 2.5 • The usual suspects: +, -, /, *, % • Range Operator • #set ($numbers = [ 1..100 ]) creates a list of integers from 1 to 100 ApacheCon US 2009
    29. 29. Velocity Operators Fun fa suppo ct: Sin ce Ver rts all si arithm numb on 1.5, Velo er typ etics w as inte es. Be city • Arithmetic operators ger on fore, a ly. ll • #set ($foo = 5 / 2 ) ## is 2! #set ($foo = 5.0 / 2) ## is 2.5 • The usual suspects: +, -, /, *, % • Range Operator • #set ($numbers = [ 1..100 ]) creates a list of integers from 1 to 100 ApacheCon US 2009
    30. 30. Misc.Velocity • Boolean operators for conditionals • !, &&, ||, ==, <=, <, >, >= • not, and, or, eq, ne, gt, ge, lt, le for convenience in e.g. XML templates • For == and !=, if the operands are not of the same class, their toString() values are compared ApacheCon US 2009
    31. 31. Velocity Strings • String interpolation for #set(), macro args and method args: • #set( $foo = 3.5 ) #set( $foo = "Value was $foo" ) $foo is now "Value was 3.5" • Force a reference to be a String: • #set ($foo = "$foo") • Use ' to avoid interpolation: • #set ($foo = '$foo') ApacheCon US 2009
    32. 32. Velocity Context • Context objects are accessible in templates • Map of names (${foo}) to arbitrary objects • Templates can only access what is in the context • There is no way to create Java objects except through context elements • Velocity can restrict which methods and fields on a context object are available ApacheCon US 2009
    33. 33. Velocity Context Example public static void main(String [] args) throws Exceptions{cre Thi ates $ {user} and $ VelocityContext {cliche context = new VelocityContext(); } context.put("user", "Velocity User"); context.put("cliche", "Hello World!"); VelocityEngine engine = new VelocityEngine(); Template template = engine.getTemplate(args[0]); Writer out = new OutputStreamWriter(System.out); template.merge(context, out); out.flush(); } ApacheCon US 2009
    34. 34. Velocity Context Template #if ($!{user}) Hello, ${user}! #end Here is a cliche: ${cliche} ApacheCon US 2009
    35. 35. Velocity Context Template $!{use r}  is a eleme n nt in t ifty way to he con test w text e hether xists a nd is n the user on-nu ll. #if ($!{user}) Hello, ${user}! #end Here is a cliche: ${cliche} ApacheCon US 2009
    36. 36. Velocity Context Result Hello, Velocity User! Here is a cliche: Hello, World! ApacheCon US 2009
    37. 37. Interaction with the Context • The real power of Velocity • Uses runtime reflection • All public methods in public classes are available • Shortcut notation for property access ($a.b vs $a.getB()) • Type promotion as Java does • Method parameters can not be omitted! (this is not perl!) ApacheCon US 2009
    38. 38. Interaction with the Context Trivia: • The real power of Velocity Also, u p • anoth ublic meth er gre Uses runtime reflection o at way ds in publi to spe c sing in nd ho classes! Ign • ner cla All public methods in public classes are sses c urs de an be o buggi ring this is icky. T ng! available ry to a void it . • Shortcut notation for property access ($a.b vs $a.getB()) • Type promotion as Java does • Method parameters can not be omitted! (this is not perl!) ApacheCon US 2009
    39. 39. Velocity Tools • A "tool" is a context object that exposes useful methods to a template, e.g date formatting or localization • A "toolbox" is a collection of useful Java classes • The Velocity Tools sub-project offers: • GenericTools All-purpose tools • VelocityView Webapp centric tools • VelocityStruts Velocity as Struts 1.x View • Other toolboxes on the web ApacheCon US 2009
    40. 40. VelocityViewServlet • VelocityViewServlet renders arbitrary Templates through web.xml mapping • XML config file to define tools • Different tool scopes/lifecycles: • application, session, request • Request, Response, Session and ServletContext objects are exposed to templates ApacheCon US 2009
    41. 41. Demo #5:VelocityView • Uses VelocityTools 2.0 (beta4 is the current release) • VelocityViewServlet does the work • Uses LinkTool, ParameterTool, EscapeTool • ($link, $params, and $esc) • A custom tool: AddressBook is a ~30 line POJO • Only one template: index.vm (~50 lines) • ~20 lines of config (including web.xml) ApacheCon US 2009
    42. 42. Advanced Velocity • Custom directives can be created and integrated in the Velocity parser (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. • Introspector for method and property access can be customized or replaced with user code ApacheCon US 2009
    43. 43. Hacking Velocity • Velocity Template Language (VTL) is defined in JavaCC grammar • VTL itself can be changed or extended (requires recompilation of velocity.jar) • More “Advanced Velocity“ at http:// wiki.apache.org/velocity/HackingVelocity ApacheCon US 2009
    44. 44. Other Velocity uses • Velocity Subprojects • Texen for generic text generation • Anakia for XML to documentation • Apache Torque – generates Java and SQL code from templates • VelocityViewTag – Embed Velocity in JSP • Velosurf – Generate SQL Web Views ApacheCon US 2009
    45. 45. Questions?
    46. 46. Where to go from here • Velocity Web Site • http://velocity.apache.org/ • Velocity Mailing Lists • http://velocity.apache.org/contact.html • Velocity Wiki • http://wiki.apache.org/velocity/ • Slides at the US ApacheCon 2009 web site and on slideshare.net ApacheCon US 2009
    47. 47. Thanks for your interest in Velocity!

    ×