SlideShare una empresa de Scribd logo
1 de 47
An Introduction to
Apache Velocity 1.6
      Henning Schmiedehausen
       henning@apache.org

 ApacheCon 2009, Oakland, CA, U.S.A.
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
Velocity Context Template


#if ($!{user})
 Hello, ${user}!
#end
Here is a cliche: ${cliche}




                              ApacheCon US 2009
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
Velocity Context Result



Hello, Velocity User!


Here is a cliche: Hello, World!




                           ApacheCon US 2009
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
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
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
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
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
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
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
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
Questions?
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
Thanks for your
interest in Velocity!

Más contenido relacionado

La actualidad más candente

MIND sweeping introduction to PHP
MIND sweeping introduction to PHPMIND sweeping introduction to PHP
MIND sweeping introduction to PHPBUDNET
 
Xslate sv perl-2013-7-11
Xslate sv perl-2013-7-11Xslate sv perl-2013-7-11
Xslate sv perl-2013-7-11Goro Fuji
 
Class 3 - PHP Functions
Class 3 - PHP FunctionsClass 3 - PHP Functions
Class 3 - PHP FunctionsAhmed Swilam
 
Php server variables
Php server variablesPhp server variables
Php server variablesJIGAR MAKHIJA
 
Php on the Web and Desktop
Php on the Web and DesktopPhp on the Web and Desktop
Php on the Web and DesktopElizabeth Smith
 
Thymeleaf Introduction
Thymeleaf IntroductionThymeleaf Introduction
Thymeleaf IntroductionAnthony Chen
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Developmentjsmith92
 
Class 2 - Introduction to PHP
Class 2 - Introduction to PHPClass 2 - Introduction to PHP
Class 2 - Introduction to PHPAhmed Swilam
 
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Muhamad Al Imran
 
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Muhamad Al Imran
 
SPL to the Rescue - Tek 09
SPL to the Rescue - Tek 09SPL to the Rescue - Tek 09
SPL to the Rescue - Tek 09Elizabeth Smith
 
Open Source Package PHP & MySQL
Open Source Package PHP & MySQLOpen Source Package PHP & MySQL
Open Source Package PHP & MySQLkalaisai
 

La actualidad más candente (20)

PHP - Introduction to PHP
PHP -  Introduction to PHPPHP -  Introduction to PHP
PHP - Introduction to PHP
 
PHP Basic
PHP BasicPHP Basic
PHP Basic
 
MIND sweeping introduction to PHP
MIND sweeping introduction to PHPMIND sweeping introduction to PHP
MIND sweeping introduction to PHP
 
Xslate sv perl-2013-7-11
Xslate sv perl-2013-7-11Xslate sv perl-2013-7-11
Xslate sv perl-2013-7-11
 
Class 3 - PHP Functions
Class 3 - PHP FunctionsClass 3 - PHP Functions
Class 3 - PHP Functions
 
Php server variables
Php server variablesPhp server variables
Php server variables
 
Php on the Web and Desktop
Php on the Web and DesktopPhp on the Web and Desktop
Php on the Web and Desktop
 
Thymeleaf Introduction
Thymeleaf IntroductionThymeleaf Introduction
Thymeleaf Introduction
 
PHP for hacks
PHP for hacksPHP for hacks
PHP for hacks
 
Javascript
JavascriptJavascript
Javascript
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Development
 
rtwerewr
rtwerewrrtwerewr
rtwerewr
 
PHP Web Programming
PHP Web ProgrammingPHP Web Programming
PHP Web Programming
 
Php mysql
Php mysqlPhp mysql
Php mysql
 
Class 2 - Introduction to PHP
Class 2 - Introduction to PHPClass 2 - Introduction to PHP
Class 2 - Introduction to PHP
 
Php functions
Php functionsPhp functions
Php functions
 
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
 
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
 
SPL to the Rescue - Tek 09
SPL to the Rescue - Tek 09SPL to the Rescue - Tek 09
SPL to the Rescue - Tek 09
 
Open Source Package PHP & MySQL
Open Source Package PHP & MySQLOpen Source Package PHP & MySQL
Open Source Package PHP & MySQL
 

Destacado

Velocity tips and tricks
Velocity tips and tricksVelocity tips and tricks
Velocity tips and tricksdotCMS
 
E marketer mobile_display_advertising-aspirations_revelations_and_frustrations
E marketer mobile_display_advertising-aspirations_revelations_and_frustrationsE marketer mobile_display_advertising-aspirations_revelations_and_frustrations
E marketer mobile_display_advertising-aspirations_revelations_and_frustrationsAdCMO
 
Folleto School Travel Soluciones Para Grupos
Folleto School Travel Soluciones Para GruposFolleto School Travel Soluciones Para Grupos
Folleto School Travel Soluciones Para GruposASTEX
 
Rules of business amended 16th august, 2012
Rules of business amended 16th august, 2012Rules of business amended 16th august, 2012
Rules of business amended 16th august, 2012zubeditufail
 
2010 Potential China Pe Investment Themes Updated Aug
2010 Potential China Pe Investment Themes Updated Aug2010 Potential China Pe Investment Themes Updated Aug
2010 Potential China Pe Investment Themes Updated AugKC Yoon
 
Presentación1 juan angel
Presentación1 juan angelPresentación1 juan angel
Presentación1 juan angelFYR2000
 
Regala una experiencia de golden gift
Regala una experiencia de golden giftRegala una experiencia de golden gift
Regala una experiencia de golden giftsenaespecializaciongp
 
Innovación 101: Innovación para empresarios que no tienen tiempo.
Innovación 101: Innovación para empresarios que no tienen tiempo.Innovación 101: Innovación para empresarios que no tienen tiempo.
Innovación 101: Innovación para empresarios que no tienen tiempo.Rodrigo Peñalba
 
FIND OTHER HEALTH LAWYERSpdf
FIND OTHER HEALTH LAWYERSpdfFIND OTHER HEALTH LAWYERSpdf
FIND OTHER HEALTH LAWYERSpdfRashid Rashid
 
GENERALIDADES DE AuUTOESTIMA
GENERALIDADES DE AuUTOESTIMAGENERALIDADES DE AuUTOESTIMA
GENERALIDADES DE AuUTOESTIMAIlse Villamil
 
Trias - yearly report 2014
Trias - yearly report 2014Trias - yearly report 2014
Trias - yearly report 2014Trias ngo
 
Near Eastside Neighborhood Summit - December 12, 2013
Near Eastside Neighborhood Summit - December 12, 2013Near Eastside Neighborhood Summit - December 12, 2013
Near Eastside Neighborhood Summit - December 12, 2013NESCommunityBuilder
 
Alimentos funcionales presentacion
Alimentos funcionales presentacionAlimentos funcionales presentacion
Alimentos funcionales presentacionMauro Orna Gamboa
 
Dr Dev Kambhampati | Doing Business in Philippines- 2013 Country Commercial G...
Dr Dev Kambhampati | Doing Business in Philippines- 2013 Country Commercial G...Dr Dev Kambhampati | Doing Business in Philippines- 2013 Country Commercial G...
Dr Dev Kambhampati | Doing Business in Philippines- 2013 Country Commercial G...Dr Dev Kambhampati
 

Destacado (20)

Velocity tips and tricks
Velocity tips and tricksVelocity tips and tricks
Velocity tips and tricks
 
Cv Eg Nicolo 3
Cv Eg Nicolo 3Cv Eg Nicolo 3
Cv Eg Nicolo 3
 
New york
New yorkNew york
New york
 
Evaluacion 3
Evaluacion 3Evaluacion 3
Evaluacion 3
 
E marketer mobile_display_advertising-aspirations_revelations_and_frustrations
E marketer mobile_display_advertising-aspirations_revelations_and_frustrationsE marketer mobile_display_advertising-aspirations_revelations_and_frustrations
E marketer mobile_display_advertising-aspirations_revelations_and_frustrations
 
Folleto School Travel Soluciones Para Grupos
Folleto School Travel Soluciones Para GruposFolleto School Travel Soluciones Para Grupos
Folleto School Travel Soluciones Para Grupos
 
Rules of business amended 16th august, 2012
Rules of business amended 16th august, 2012Rules of business amended 16th august, 2012
Rules of business amended 16th august, 2012
 
2010 Potential China Pe Investment Themes Updated Aug
2010 Potential China Pe Investment Themes Updated Aug2010 Potential China Pe Investment Themes Updated Aug
2010 Potential China Pe Investment Themes Updated Aug
 
Presentación1 juan angel
Presentación1 juan angelPresentación1 juan angel
Presentación1 juan angel
 
Regala una experiencia de golden gift
Regala una experiencia de golden giftRegala una experiencia de golden gift
Regala una experiencia de golden gift
 
Higiene industrial
Higiene industrialHigiene industrial
Higiene industrial
 
Innovación 101: Innovación para empresarios que no tienen tiempo.
Innovación 101: Innovación para empresarios que no tienen tiempo.Innovación 101: Innovación para empresarios que no tienen tiempo.
Innovación 101: Innovación para empresarios que no tienen tiempo.
 
FIND OTHER HEALTH LAWYERSpdf
FIND OTHER HEALTH LAWYERSpdfFIND OTHER HEALTH LAWYERSpdf
FIND OTHER HEALTH LAWYERSpdf
 
GENERALIDADES DE AuUTOESTIMA
GENERALIDADES DE AuUTOESTIMAGENERALIDADES DE AuUTOESTIMA
GENERALIDADES DE AuUTOESTIMA
 
Trias - yearly report 2014
Trias - yearly report 2014Trias - yearly report 2014
Trias - yearly report 2014
 
Near Eastside Neighborhood Summit - December 12, 2013
Near Eastside Neighborhood Summit - December 12, 2013Near Eastside Neighborhood Summit - December 12, 2013
Near Eastside Neighborhood Summit - December 12, 2013
 
El placer de escribir.
El placer de escribir.El placer de escribir.
El placer de escribir.
 
Alimentos funcionales presentacion
Alimentos funcionales presentacionAlimentos funcionales presentacion
Alimentos funcionales presentacion
 
Dr Dev Kambhampati | Doing Business in Philippines- 2013 Country Commercial G...
Dr Dev Kambhampati | Doing Business in Philippines- 2013 Country Commercial G...Dr Dev Kambhampati | Doing Business in Philippines- 2013 Country Commercial G...
Dr Dev Kambhampati | Doing Business in Philippines- 2013 Country Commercial G...
 
Nombres y logos
Nombres y logosNombres y logos
Nombres y logos
 

Similar a Apache Velocity 1.6

8. Php MongoDB stergerea unui document
8. Php MongoDB stergerea unui document8. Php MongoDB stergerea unui document
8. Php MongoDB stergerea unui documentRazvan Raducanu, PhD
 
7. Php MongoDB editarea unui document
7. Php MongoDB editarea unui document7. Php MongoDB editarea unui document
7. Php MongoDB editarea unui documentRazvan Raducanu, PhD
 
5. Php MongoDB vederea unui singur document
5. Php MongoDB vederea unui singur document5. Php MongoDB vederea unui singur document
5. Php MongoDB vederea unui singur documentRazvan Raducanu, PhD
 
9. Php MongoDB cautarea unui document
9. Php MongoDB cautarea unui document9. Php MongoDB cautarea unui document
9. Php MongoDB cautarea unui documentRazvan Raducanu, PhD
 
Side by Side - Scala and Java Adaptations of Martin Fowler’s Javascript Refac...
Side by Side - Scala and Java Adaptations of Martin Fowler’s Javascript Refac...Side by Side - Scala and Java Adaptations of Martin Fowler’s Javascript Refac...
Side by Side - Scala and Java Adaptations of Martin Fowler’s Javascript Refac...Philip Schwarz
 
6. Php MongoDB adaugarea unui document
6. Php MongoDB adaugarea unui document6. Php MongoDB adaugarea unui document
6. Php MongoDB adaugarea unui documentRazvan Raducanu, PhD
 
Shell Script Disk Usage Report and E-Mail Current Threshold Status
Shell Script  Disk Usage Report and E-Mail Current Threshold StatusShell Script  Disk Usage Report and E-Mail Current Threshold Status
Shell Script Disk Usage Report and E-Mail Current Threshold StatusVCP Muthukrishna
 
Meet Up - Spark Stream Processing + Kafka
Meet Up - Spark Stream Processing + KafkaMeet Up - Spark Stream Processing + Kafka
Meet Up - Spark Stream Processing + KafkaKnoldus Inc.
 
Type safe embedded domain-specific languages
Type safe embedded domain-specific languagesType safe embedded domain-specific languages
Type safe embedded domain-specific languagesArthur Xavier
 
Workshop on command line tools - day 2
Workshop on command line tools - day 2Workshop on command line tools - day 2
Workshop on command line tools - day 2Leandro Lima
 
Dealing with Legacy Perl Code - Peter Scott
Dealing with Legacy Perl Code - Peter ScottDealing with Legacy Perl Code - Peter Scott
Dealing with Legacy Perl Code - Peter ScottO'Reilly Media
 
Pitfalls to Avoid for Cascade Server Newbies by Lisa Hall
Pitfalls to Avoid for Cascade Server Newbies by Lisa HallPitfalls to Avoid for Cascade Server Newbies by Lisa Hall
Pitfalls to Avoid for Cascade Server Newbies by Lisa Hallhannonhill
 
Rails Presentation - Technology Books, Tech Conferences
 Rails Presentation - Technology Books, Tech Conferences Rails Presentation - Technology Books, Tech Conferences
Rails Presentation - Technology Books, Tech Conferencestutorialsruby
 
jQuery%20on%20Rails%20Presentation
jQuery%20on%20Rails%20PresentationjQuery%20on%20Rails%20Presentation
jQuery%20on%20Rails%20Presentationguestcf600a
 
jQuery%20on%20Rails%20Presentation
jQuery%20on%20Rails%20PresentationjQuery%20on%20Rails%20Presentation
jQuery%20on%20Rails%20Presentationguestcf600a
 
JQuery-Tutorial" />
  JQuery-Tutorial" />  JQuery-Tutorial" />
JQuery-Tutorial" />tutorialsruby
 

Similar a Apache Velocity 1.6 (20)

8. Php MongoDB stergerea unui document
8. Php MongoDB stergerea unui document8. Php MongoDB stergerea unui document
8. Php MongoDB stergerea unui document
 
7. Php MongoDB editarea unui document
7. Php MongoDB editarea unui document7. Php MongoDB editarea unui document
7. Php MongoDB editarea unui document
 
5. Php MongoDB vederea unui singur document
5. Php MongoDB vederea unui singur document5. Php MongoDB vederea unui singur document
5. Php MongoDB vederea unui singur document
 
9. Php MongoDB cautarea unui document
9. Php MongoDB cautarea unui document9. Php MongoDB cautarea unui document
9. Php MongoDB cautarea unui document
 
Side by Side - Scala and Java Adaptations of Martin Fowler’s Javascript Refac...
Side by Side - Scala and Java Adaptations of Martin Fowler’s Javascript Refac...Side by Side - Scala and Java Adaptations of Martin Fowler’s Javascript Refac...
Side by Side - Scala and Java Adaptations of Martin Fowler’s Javascript Refac...
 
6. Php MongoDB adaugarea unui document
6. Php MongoDB adaugarea unui document6. Php MongoDB adaugarea unui document
6. Php MongoDB adaugarea unui document
 
Shell Script Disk Usage Report and E-Mail Current Threshold Status
Shell Script  Disk Usage Report and E-Mail Current Threshold StatusShell Script  Disk Usage Report and E-Mail Current Threshold Status
Shell Script Disk Usage Report and E-Mail Current Threshold Status
 
Unfiltered Unveiled
Unfiltered UnveiledUnfiltered Unveiled
Unfiltered Unveiled
 
Jquery
JqueryJquery
Jquery
 
Meet Up - Spark Stream Processing + Kafka
Meet Up - Spark Stream Processing + KafkaMeet Up - Spark Stream Processing + Kafka
Meet Up - Spark Stream Processing + Kafka
 
Type safe embedded domain-specific languages
Type safe embedded domain-specific languagesType safe embedded domain-specific languages
Type safe embedded domain-specific languages
 
Workshop on command line tools - day 2
Workshop on command line tools - day 2Workshop on command line tools - day 2
Workshop on command line tools - day 2
 
PHP POWERPOINT SLIDES
PHP POWERPOINT SLIDESPHP POWERPOINT SLIDES
PHP POWERPOINT SLIDES
 
Dealing with Legacy Perl Code - Peter Scott
Dealing with Legacy Perl Code - Peter ScottDealing with Legacy Perl Code - Peter Scott
Dealing with Legacy Perl Code - Peter Scott
 
Pitfalls to Avoid for Cascade Server Newbies by Lisa Hall
Pitfalls to Avoid for Cascade Server Newbies by Lisa HallPitfalls to Avoid for Cascade Server Newbies by Lisa Hall
Pitfalls to Avoid for Cascade Server Newbies by Lisa Hall
 
Ip lab
Ip labIp lab
Ip lab
 
Rails Presentation - Technology Books, Tech Conferences
 Rails Presentation - Technology Books, Tech Conferences Rails Presentation - Technology Books, Tech Conferences
Rails Presentation - Technology Books, Tech Conferences
 
jQuery%20on%20Rails%20Presentation
jQuery%20on%20Rails%20PresentationjQuery%20on%20Rails%20Presentation
jQuery%20on%20Rails%20Presentation
 
jQuery%20on%20Rails%20Presentation
jQuery%20on%20Rails%20PresentationjQuery%20on%20Rails%20Presentation
jQuery%20on%20Rails%20Presentation
 
JQuery-Tutorial" />
  JQuery-Tutorial" />  JQuery-Tutorial" />
JQuery-Tutorial" />
 

Último

"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 

Último (20)

"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 

Apache Velocity 1.6

  • 1. An Introduction to Apache Velocity 1.6 Henning Schmiedehausen henning@apache.org ApacheCon 2009, Oakland, CA, U.S.A.
  • 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. Velocity Context Template #if ($!{user}) Hello, ${user}! #end Here is a cliche: ${cliche} ApacheCon US 2009
  • 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. Velocity Context Result Hello, Velocity User! Here is a cliche: Hello, World! ApacheCon US 2009
  • 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. 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. 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. 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. 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. 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. 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. 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
  • 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. Thanks for your interest in Velocity!

Notas del editor

  1. mvn exec:java -Dexec.mainClass=org.apache.velocity.contextdemo.ContextDemo -Dexec.args=src/main/templates/Test.vm