Math
Velocity has a handful of built-in mathematical functions that can be used in
templates with the set
directive. The following equations are
examples of addition, subtraction, multiplication and division, respectively:
#set( $foo = $bar + 3 )
#set( $foo = $bar - 4 )
#set( $foo = $bar * 6 )
#set( $foo = $bar / 2 )
When a division operation is performed between two integers, the result will be an
integer, as the fractional portion is discarded. Any remainder can be obtained by
using the modulus (%
) operator:
#set( $foo = $bar % 5 )
Range Operator
The range operator can be used in conjunction with #set
and
#foreach
statements. Useful for its ability to produce an
object array containing integers, the range operator has the following construction:
[n..m]
Both n
and m
must either be or produce integers. Whether m
is greater than or less than n
will not
matter; in this case the range will simply count down. Examples showing the use of
the range operator as provided below:
First example:
#foreach( $foo in [1..5] )
$foo
#end
Second example:
#foreach( $bar in [2..-2] )
$bar
#end
Third example:
#set( $arr = [0..1] )
#foreach( $i in $arr )
$i
#end
Fourth example:
[1..3]
Produces the following output:
First example:
1 2 3 4 5
Second example:
2 1 0 -1 -2
Third example:
0 1
Fourth example:
[1..3]
#set
and #foreach
directives, as demonstrated
in the fourth example. Web page designers concerned with making tables a standard size, but where some will not have enough data to fill the table, will find the range operator particularly useful.
Advanced Issues: Escaping and !
When a reference is silenced with the !
character and the
!
character preceded by an \
escape character,
the reference is handled in a special way. Note the differences between regular
escaping, and the special case where \
precedes !
follows it:
#set( $foo = "bar" )
$\!foo
$\!{foo}
$\\!foo
$\\\!foo
This renders as:
$!foo
$!{foo}
$\!foo
$\\!foo
Contrast this with regular escaping, where \
precedes
$
:
\$foo
\$!foo
\$!{foo}
\\$!{foo}
This renders as:
$foo
$!foo
$!{foo}
\bar