Bug fixed (FREEMARKER-70): The usage of loop variable built-ins, like loopVar?index...
[incubator-freemarker.git] / src / manual / en_US / book.xml
1 <?xml version="1.0" encoding="UTF-8"?>
2 <!--
3 Licensed to the Apache Software Foundation (ASF) under one
4 or more contributor license agreements. See the NOTICE file
5 distributed with this work for additional information
6 regarding copyright ownership. The ASF licenses this file
7 to you under the Apache License, Version 2.0 (the
8 "License"); you may not use this file except in compliance
9 with the License. You may obtain a copy of the License at
10
11 http://www.apache.org/licenses/LICENSE-2.0
12
13 Unless required by applicable law or agreed to in writing,
14 software distributed under the License is distributed on an
15 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16 KIND, either express or implied. See the License for the
17 specific language governing permissions and limitations
18 under the License.
19 -->
20 <book conformance="docgen" version="5.0" xml:lang="en"
21 xmlns="http://docbook.org/ns/docbook"
22 xmlns:xlink="http://www.w3.org/1999/xlink"
23 xmlns:xi="http://www.w3.org/2001/XInclude"
24 xmlns:ns5="http://www.w3.org/1999/xhtml"
25 xmlns:ns4="http://www.w3.org/2000/svg"
26 xmlns:ns3="http://www.w3.org/1998/Math/MathML"
27 xmlns:ns="http://docbook.org/ns/docbook">
28 <info>
29 <title>Apache FreeMarker Manual</title>
30
31 <titleabbrev>Manual</titleabbrev>
32
33 <productname>Freemarker 2.3.27</productname>
34 </info>
35
36 <preface role="index.html" xml:id="preface">
37 <title>What is Apache FreeMarker?</title>
38
39 <para>FreeMarker is a <emphasis>template engine</emphasis>: a generic tool
40 to generate text output (HTML web pages, e-mails, configuration files,
41 source code, etc.) based on templates and changing data. It's not an
42 application for end-users in itself, but a Java library, a component that
43 programmers can embed into their products.</para>
44
45 <para>Templates are written in the FreeMarker Template Language (FTL).
46 It's a simple, specialized language, <emphasis>not</emphasis> a full-blown
47 programming language like PHP. You are meant to prepare the data to
48 display in a real programming language, like issue database queries and do
49 business calculations, and then the template displays that already
50 prepared data. In the template you are focusing on how to present the
51 data, and outside the template you are focusing on what data to
52 present.</para>
53
54 <mediaobject>
55 <imageobject>
56 <imagedata fileref="figures/overview.png"/>
57 </imageobject>
58 </mediaobject>
59
60 <para>This approach is often referred to as the <link
61 linkend="gloss.MVC">MVC (Model View Controller) pattern</link>, and is
62 particularly popular for dynamic web pages. It helps in separating web
63 page designers (HTML authors) from developers (Java programmers usually).
64 Designers won't face complicated logic in templates, and can change the
65 appearance of a page without programmers having to change or recompile
66 code.</para>
67
68 <para>While FreeMarker was originally created for generating HTML pages in
69 MVC web application frameworks, it isn't bound to servlets or HTML or
70 anything web-related. It's used in non-web application environments as
71 well.</para>
72
73 <para>FreeMarker is <link
74 xlink:href="http://www.fsf.org/philosophy/free-sw.html">Free</link>,
75 released under the Apache License, Version 2.0.</para>
76
77 <para><emphasis role="bold">Disclaimer: </emphasis><emphasis>Apache
78 FreeMarker is an effort undergoing incubation at The Apache Software
79 Foundation (ASF), sponsored by the <link
80 xlink:href="http://incubator.apache.org">Apache Incubator</link>.
81 Incubation is required of all newly accepted projects until a further
82 review indicates that the infrastructure, communications, and decision
83 making process have stabilized in a manner consistent with other
84 successful ASF projects. While incubation status is not necessarily a
85 reflection of the completeness or stability of the code, it does indicate
86 that the project has yet to be fully endorsed by the
87 ASF.</emphasis></para>
88 </preface>
89
90 <part xml:id="dgui">
91 <title>Template Author's Guide</title>
92
93 <chapter xml:id="dgui_quickstart">
94 <title>Getting Started</title>
95
96 <para>This chapter is a very rough introduction to FreeMarker. The
97 chapters after this will go over things in much greater detail.
98 Nonetheless, once you have read this chapter, you will be able to write
99 simple but useful FreeMarker templates.</para>
100
101 <section xml:id="dgui_quickstart_basics">
102 <title>Template + data-model = output</title>
103
104 <para>Let's assume that you need a HTML page on a website, similar to
105 this:</para>
106
107 <programlisting role="output">&lt;html&gt;
108 &lt;head&gt;
109 &lt;title&gt;Welcome!&lt;/title&gt;
110 &lt;/head&gt;
111 &lt;body&gt;
112 &lt;h1&gt;Welcome <emphasis>John Doe</emphasis>!&lt;/h1&gt;
113 &lt;p&gt;Our latest product:
114 &lt;a href="<emphasis>products/greenmouse.html</emphasis>"&gt;<emphasis>green mouse</emphasis>&lt;/a&gt;!
115 &lt;/body&gt;
116 &lt;/html&gt;</programlisting>
117
118 <para>But the user's name ("John Doe" above) depends on who the
119 logged-in user is, and the latest product information should come from
120 a database. Because this data changes, you cannot you cannot use
121 static HTML. Instead, you can use a <emphasis
122 role="term">template</emphasis> of the desired output. The template is
123 the same as the static HTML would be, except that it contains some
124 instructions to FreeMarker that makes it dynamic:</para>
125
126 <programlisting role="template" xml:id="example.first">&lt;html&gt;
127 &lt;head&gt;
128 &lt;title&gt;Welcome!&lt;/title&gt;
129 &lt;/head&gt;
130 &lt;body&gt;
131 &lt;h1&gt;Welcome <emphasis>${user}</emphasis>!&lt;/h1&gt;
132 &lt;p&gt;Our latest product:
133 &lt;a href="<emphasis>${latestProduct.url}</emphasis>"&gt;<emphasis>${latestProduct.name}</emphasis>&lt;/a&gt;!
134 &lt;/body&gt;
135 &lt;/html&gt;</programlisting>
136
137 <para>The template is stored on the Web server, usually just like the
138 static HTML page would be. But whenever someone visits this page,
139 FreeMarker will step in and transform the template on-the-fly to plain
140 HTML by replacing the
141 <literal>${<replaceable>...</replaceable>}</literal>-s with up-to-date
142 content, and send the result to the visitor's Web browser. So the
143 visitor's Web browser will receive something like the first example
144 HTML (i.e., plain HTML without FreeMarker instructions), and it will
145 not perceive that FreeMarker is used on the server. (Of course, the
146 template file stored on the Web server is not changed by this; the
147 substitutions only appear in the Web server's response.)</para>
148
149 <para>Note that the template doesn't contain the programming logic to
150 find out who the current visitor is, or to query the database to get
151 the latest product. The data to be displayed is prepared outside
152 FreeMarker, usually by parts written in some <quote>real</quote>
153 programming language like Java. The template author needn't know how
154 these values were calculated. In fact, the way these values are
155 calculated can be completely changed while the templates can remain
156 exactly the same, and also, the look of the page can be completely
157 changed without touching anything but the template. This separation of
158 presentation logic and business logic can be especially useful when
159 the template authors (designers) and the programmers are different
160 individuals, but also helps managing application complexity if they
161 are the same person. Keeping templates focused on presentation issues
162 (visual design, layout and formatting) is a key for using template
163 engines like FreeMarker efficiently.</para>
164
165 <para><indexterm>
166 <primary>data-model</primary>
167 </indexterm>The totality of data that was prepared for the template
168 is called the <emphasis role="term">data-model</emphasis>. As far as
169 the template author is concerned, the data-model is a tree-like
170 structure (like folders and files on your hard disk), which, in this
171 case, could be visualized as:</para>
172
173 <programlisting role="dataModel">(root)
174 |
175 +- <emphasis>user</emphasis> = "Big Joe"
176 |
177 +- <emphasis>latestProduct</emphasis>
178 |
179 +- <emphasis>url</emphasis> = "products/greenmouse.html"
180 |
181 +- <emphasis>name</emphasis> = "green mouse"</programlisting>
182
183 <note>
184 <para>The above is just a visualization; the data-model is not in a
185 textual format, it's from Java objects. For the Java programmers,
186 the root is perhaps a Java object with <literal>getUser()</literal>
187 and <literal>getLatestProduct()</literal> methods, or maybe a Java
188 <literal>Map</literal> with <literal>"user"</literal> and
189 <literal>"latestProducts"</literal> keys. Similarly,
190 <literal>latestProduct</literal> is perhaps a Java Object with
191 <literal>getUrl()</literal> and <literal>getName()</literal>
192 methods.</para>
193 </note>
194
195 <para>Earlier, you have picked values from this data-model, with the
196 <literal>user</literal> and <literal>latestProduct.name</literal>
197 expressions. If we go on with the analogy that the data model is like
198 a file system, then <quote>(root)</quote> and
199 <literal>latestProduct</literal> correspond to directories (folders),
200 and <literal>user</literal>, <literal>url</literal> and
201 <literal>name</literal> are files in those directories.</para>
202
203 <para>To recapitulate, a template and a data-model is needed for
204 FreeMarker to generate the output (like the HTML shown first):</para>
205
206 <para><phrase role="markedTemplate">Template</phrase> + <phrase
207 role="markedDataModel">data-model</phrase> = <phrase
208 role="markedOutput">output</phrase></para>
209 </section>
210
211 <section xml:id="dgui_quickstart_datamodel">
212 <title>The data-model at a glance</title>
213
214 <para>As you have seen, the data-model is basically a tree. This tree
215 can be arbitrarily complicated and deep, for example:</para>
216
217 <programlisting role="dataModel"
218 xml:id="example.qStart.dataModelWithHashes">(root)
219 |
220 +- animals
221 | |
222 | +- mouse
223 | | |
224 | | +- size = "small"
225 | | |
226 | | +- price = 50
227 | |
228 | +- elephant
229 | | |
230 | | +- size = "large"
231 | | |
232 | | +- price = 5000
233 | |
234 | +- python
235 | |
236 | +- size = "medium"
237 | |
238 | +- price = 4999
239 |
240 +- message = "It is a test"
241 |
242 +- misc
243 |
244 +- foo = "Something"</programlisting>
245
246 <para>The variables that act like directories (the root,
247 <literal>animals</literal>, <literal>mouse</literal>,
248 <literal>elephant</literal>, <literal>python</literal>,
249 <literal>misc</literal>) are called <emphasis
250 role="term">hashes</emphasis>. Hashes store other variables (the so
251 called <anchor xml:id="topic.dataModel.subVar"/><emphasis>sub
252 variables</emphasis>) by a lookup name (e.g., <quote>animals</quote>,
253 <quote>mouse</quote> or <quote>price</quote>).</para>
254
255 <para>The variables that store a single value
256 (<literal>size</literal>, <literal>price</literal>,
257 <literal>message</literal> and <literal>foo</literal>) are called
258 <emphasis role="term">scalars</emphasis>.</para>
259
260 <para><anchor xml:id="topic.qStart.accessVariables"/>When you want to
261 use a subvariable in a template, you specify its path from the root,
262 and separate the steps with dots. To access the
263 <literal>price</literal> of a <literal>mouse</literal>, you start from
264 the root and go into <literal>animals</literal>, and then go into
265 <literal>mouse</literal> then go into <literal>price</literal>. So you
266 write <literal>animals.mouse.price</literal>.</para>
267
268 <para>Another important kind of variables are <emphasis
269 role="term">sequences</emphasis>. They store subvariables like hashes,
270 but here subvariables doesn't have a name, they are just items in a
271 list. For example, in this data-model, <literal>animals</literal> and
272 <literal>misc.fruits</literal> are sequences:</para>
273
274 <programlisting role="dataModel"
275 xml:id="example.qStart.dataModelWithSequences">(root)
276 |
277 +- animals
278 | |
279 | +- (1st)
280 | | |
281 | | +- name = "mouse"
282 | | |
283 | | +- size = "small"
284 | | |
285 | | +- price = 50
286 | |
287 | +- (2nd)
288 | | |
289 | | +- name = "elephant"
290 | | |
291 | | +- size = "large"
292 | | |
293 | | +- price = 5000
294 | |
295 | +- (3rd)
296 | |
297 | +- name = "python"
298 | |
299 | +- size = "medium"
300 | |
301 | +- price = 4999
302 |
303 +- misc
304 |
305 +- fruits
306 |
307 +- (1st) = "orange"
308 |
309 +- (2nd) = "banana"</programlisting>
310
311 <para>To access a subvariable of a sequence you use a numerical index
312 in square brackets. Indexes start from 0 (it's a programmer tradition
313 to start with 0), thus the index of the 1st item is 0, the index of
314 the 2nd item is 1, and so on. So to get the name of the first animal
315 you write <literal>animals[0].name</literal>. To get the second item
316 in <literal>misc.fruits</literal> (the string
317 <literal>"banana"</literal>) you write
318 <literal>misc.fruits[1]</literal>. (In practice, you usually just walk
319 through sequences in order, not caring about the index, but that will
320 be <link linkend="topic.tutorial.list">shown later</link>.)</para>
321
322 <para>Scalars can be further divided into these categories:</para>
323
324 <itemizedlist>
325 <listitem>
326 <para>String: Text, that is, an arbitrary sequence of characters
327 such as ''m'', ''o'', ''u'', ''s'', ''e'' above. For example the
328 <literal>name</literal>-s and <literal>size</literal>-s are
329 strings above.</para>
330 </listitem>
331
332 <listitem>
333 <para>Number: It's a numerical value, like the
334 <literal>price</literal>-s above. The string
335 <literal>"50"</literal> and the number <literal>50</literal> are
336 two totally different things in FreeMarker. The former is just a
337 sequence of two characters (which happens to be readable as a
338 number for humans), while the latter is a numerical value that you
339 can use in arithmetical calculations.</para>
340 </listitem>
341
342 <listitem>
343 <para>Date-like: Either a date-time (stores a date with time of
344 the day), or a date (no time of day), or a time (time of day, no
345 date).</para>
346 </listitem>
347
348 <listitem>
349 <para>Boolean: A true/false (yes/no, on/off, etc.) thing. Like
350 animals could have a <literal>protected</literal> subvariable,
351 which store if the animal is protected or not.</para>
352 </listitem>
353 </itemizedlist>
354
355 <para>Summary:</para>
356
357 <itemizedlist>
358 <listitem>
359 <para>The data-model can be visualized as a tree.</para>
360 </listitem>
361
362 <listitem>
363 <para>Scalars store a single value. The value can be a string or a
364 number or a date-time/date/time or a boolean.</para>
365 </listitem>
366
367 <listitem>
368 <para>Hashes are containers that store other variables and
369 associate them with a unique lookup name.</para>
370 </listitem>
371
372 <listitem>
373 <para>Sequences are containers that store other variables in an
374 ordered sequence. The stored variables can be retrieved via their
375 numerical index, starting from 0.</para>
376 </listitem>
377 </itemizedlist>
378
379 <note>
380 <para>There are other, more advanced value types that we don't cover
381 here, such as methods and directives.</para>
382 </note>
383 </section>
384
385 <section xml:id="dgui_quickstart_template">
386 <title>The template at a glance</title>
387
388 <para>The simplest template is a plain HTML file (or whatever text
389 file; FreeMarker is not confined to HTML). When the client visits that
390 page, FreeMarker will send that HTML to the client as is. However if
391 you want that page to be more dynamic then you begin to put special
392 parts into the HTML which will be understood by FreeMarker:</para>
393
394 <itemizedlist>
395 <listitem>
396 <para><literal>${<replaceable>...</replaceable>}</literal>:
397 FreeMarker will replace it in the output with the actual value of
398 the expression inside the curly brackets. They are called
399 <emphasis role="term">interpolation</emphasis>s.</para>
400 </listitem>
401
402 <listitem>
403 <para><emphasis role="term">FTL tags</emphasis> (for FreeMarker
404 Template Language tags): FTL tags are a bit similar to HTML tags,
405 but they are instructions to FreeMarker and will not be printed to
406 the output. The name of these tags start with
407 <literal>#</literal>. (User-defined FTL tags use
408 <literal>@</literal> instead of <literal>#</literal>, but they are
409 an advanced topic.)</para>
410 </listitem>
411
412 <listitem>
413 <para><emphasis role="term">Comments:</emphasis> Comments are
414 similar to HTML comments, but they are delimited by
415 <literal>&lt;#--</literal> and <literal>--&gt;</literal>. Unlike
416 HTML comments, FTL comments won't get into the output (won't be
417 visible in the page source for the visitor), because FreeMarker
418 skips them.</para>
419 </listitem>
420 </itemizedlist>
421
422 <para>Anything not an FTL tag or an interpolation or comment is
423 considered static text and will not be interpreted by FreeMarker; it
424 is just printed to the output as-is.</para>
425
426 <para>With FTL tags you refer to so-called <emphasis
427 role="term">directives</emphasis>. This is the same kind of
428 relationship as between HTML tags (e.g.:
429 <literal>&lt;table&gt;</literal> and
430 <literal>&lt;/table&gt;</literal>) and HTML elements (e.g., the
431 <literal>table</literal> element) to which you refer to with the HTML
432 tags. (If you don't understand this difference then consider "FTL tag"
433 and "directive" synonyms.)</para>
434
435 <note>
436 <para>You can easily try writing templates on <link
437 xlink:href="http://freemarker-online.kenshoo.com/">http://freemarker-online.kenshoo.com/</link></para>
438 </note>
439
440 <section>
441 <title>Some basic directives</title>
442
443 <para>Here we will look at some of the most commonly used directives
444 (<link linkend="ref_directives">but there are much
445 more</link>).</para>
446
447 <section>
448 <title>The if directive</title>
449
450 <para>With the <literal>if</literal> directive you can
451 conditionally skip a section of the template. For example, assume
452 that in the <link linkend="example.first">very first
453 example</link> you want to greet your boss, Big Joe, differently
454 than other users:</para>
455
456 <programlisting role="template">&lt;html&gt;
457 &lt;head&gt;
458 &lt;title&gt;Welcome!&lt;/title&gt;
459 &lt;/head&gt;
460 &lt;body&gt;
461 &lt;h1&gt;
462 Welcome ${user}<emphasis>&lt;#if user == "Big Joe"&gt;</emphasis>, our beloved leader<emphasis>&lt;/#if&gt;</emphasis>!
463 &lt;/h1&gt;
464 &lt;p&gt;Our latest product:
465 &lt;a href="${latestProduct.url}"&gt;${latestProduct.name}&lt;/a&gt;!
466 &lt;/body&gt;
467 &lt;/html&gt;</programlisting>
468
469 <para>Here you have told FreeMarker that the <quote>, our beloved
470 leader</quote> should be there only if the value of the variable
471 <literal>user</literal> is equal to the string <literal>"Big
472 Joe"</literal>. In general, things between <literal>&lt;#if
473 <replaceable>condition</replaceable>&gt;</literal> and
474 <literal>&lt;/#if&gt;</literal> tags are skipped if
475 <literal><replaceable>condition</replaceable></literal> is false
476 (the boolean value).</para>
477
478 <para>Let's look at
479 <literal><replaceable>condition</replaceable></literal> more
480 closely: <literal>==</literal> is an operator that tests if the
481 values at its left and right side are equivalent, and the results
482 is a boolean value, true or false accordingly. On the left side of
483 <literal>==</literal> I have <link
484 linkend="topic.qStart.accessVariables">referenced a
485 variable</link> with the syntax that should be already familiar;
486 this will be replaced with the value of the variable. In general,
487 unquoted words inside directives or interpolations are treated as
488 references to variables. On the right side I have specified a
489 literal string. Literal strings in templates must
490 <emphasis>always</emphasis> be put inside quotation marks.</para>
491
492 <para>This will print <quote>Pythons are free today!</quote> if
493 their price is 0:</para>
494
495 <programlisting role="template">&lt;#if animals.python.price == <emphasis>0</emphasis>&gt;
496 Pythons are free today!
497 &lt;/#if&gt;</programlisting>
498
499 <para>Similarly as earlier when a string was specified directly,
500 here a number is specified directly (<literal>0</literal>). Note
501 that the number is <emphasis>not</emphasis> quoted. If you quoted
502 it (<literal>"0"</literal>), FreeMarker would misinterpret it as a
503 string literal, and because the price to compare it to is a
504 number, you get an error.</para>
505
506 <para>This will print "Pythons are not free today!" if their price
507 is not 0:</para>
508
509 <programlisting role="template">&lt;#if animals.python.price <emphasis>!=</emphasis> 0&gt;
510 Pythons are not free today!
511 &lt;/#if&gt;</programlisting>
512
513 <para>As you probably guessed, <literal>!=</literal> means
514 <quote>not equals</quote>.</para>
515
516 <para>You can write things like this too (using <link
517 linkend="example.qStart.dataModelWithHashes">the data-model used
518 to demonstrate hashes</link>):</para>
519
520 <programlisting role="template">&lt;#if <emphasis>animals.python.price &lt; animals.elephant.price</emphasis>&gt;
521 Pythons are cheaper than elephants today.
522 &lt;/#if&gt;</programlisting>
523
524 <para>With the <literal>&lt;#else&gt;</literal> tag you can
525 specify what to do if the condition is false. For example:</para>
526
527 <programlisting role="template">&lt;#if animals.python.price &lt; animals.elephant.price&gt;
528 Pythons are cheaper than elephants today.
529 <emphasis>&lt;#else&gt;</emphasis>
530 Pythons are not cheaper than elephants today.
531 &lt;/#if&gt;</programlisting>
532
533 <para>This prints <quote>Pythons are cheaper than elephants
534 today.</quote> if the price of python is less than the price of
535 elephant, or else it prints <quote>Pythons are not cheaper than
536 elephants today.</quote> You can refine this further by using
537 <literal>elseif</literal>:</para>
538
539 <programlisting role="template">&lt;#if animals.python.price &lt; animals.elephant.price&gt;
540 Pythons are cheaper than elephants today.
541 <emphasis>&lt;#elseif animals.elephant.price &lt; animals.python.price&gt;</emphasis>
542 Elephants are cheaper than pythons today.
543 &lt;#else&gt;
544 Elephants and pythons cost the same today.
545 &lt;/#if&gt;</programlisting>
546
547 <para>If you have a variable with boolean value (a true/false
548 thing) then you can use it directly as the
549 <literal><replaceable>condition</replaceable></literal> of
550 <literal>if</literal>:</para>
551
552 <programlisting role="template">&lt;#if animals.python.protected&gt;
553 Pythons are protected animals!
554 &lt;/#if&gt;</programlisting>
555 </section>
556
557 <section>
558 <title>The list directive</title>
559
560 <anchor xml:id="topic.tutorial.list"/>
561
562 <para>This is needed when you want to list something. For example
563 if you merge this template with the <link
564 linkend="example.qStart.dataModelWithSequences">data-model used
565 earlier to demonstrate sequences</link>:</para>
566
567 <programlisting role="template">&lt;p&gt;We have these animals:
568 &lt;table border=1&gt;
569 <emphasis>&lt;#list animals as animal&gt;</emphasis>
570 &lt;tr&gt;&lt;td&gt;${<emphasis>animal</emphasis>.name}&lt;td&gt;${<emphasis>animal</emphasis>.price} Euros
571 <emphasis>&lt;/#list&gt;</emphasis>
572 &lt;/table&gt;</programlisting>
573
574 <para>then the output will be:</para>
575
576 <programlisting role="output">&lt;p&gt;We have these animals:
577 &lt;table border=1&gt;
578 <emphasis>&lt;tr&gt;&lt;td&gt;mouse&lt;td&gt;50 Euros
579 &lt;tr&gt;&lt;td&gt;elephant&lt;td&gt;5000 Euros
580 &lt;tr&gt;&lt;td&gt;python&lt;td&gt;4999 Euros</emphasis>
581 &lt;/table&gt;</programlisting>
582
583 <para>The generic form of the <literal>list</literal> directive
584 is:<literal> &lt;#list <replaceable>sequence</replaceable> as
585 <replaceable>loopVariable</replaceable>&gt;<replaceable>repeatThis</replaceable>&lt;/#list&gt;</literal>.
586 The <literal><replaceable>repeatThis</replaceable></literal> part
587 will be repeated for each item in the sequence that you have
588 specified with
589 <literal><replaceable>sequence</replaceable></literal>, one after
590 the other, starting from the first item. In all repetitions
591 <literal><replaceable>loopVariable</replaceable></literal> will
592 hold the value of the current item. This variable exists only
593 between the <literal>&lt;#list
594 <replaceable>...</replaceable>&gt;</literal> and
595 <literal>&lt;/#list&gt;</literal> tags.</para>
596
597 <para>The <literal><replaceable>sequence</replaceable></literal>
598 can be any kind of expression. For example we could list the
599 fruits of the example data model like this:</para>
600
601 <programlisting role="template">&lt;ul&gt;
602 <emphasis>&lt;#list misc.fruits as fruit&gt;</emphasis>
603 &lt;li&gt;${fruit}
604 <emphasis>&lt;/#list&gt;</emphasis>
605 &lt;/ul&gt;</programlisting>
606
607 <para>The <literal>misc.fruits</literal> expression should be
608 familiar to you; it <link
609 linkend="topic.qStart.accessVariables">references a variable in
610 the data-model</link>.</para>
611
612 <para>A problem with the above example is that if we happen to
613 have 0 fruits, it will still print an empty
614 <literal>&lt;ul&gt;&lt;/ul&gt;</literal> instead of just nothing.
615 To avoid that, you can use this form of
616 <literal>list</literal>:</para>
617
618 <programlisting role="template">&lt;#list misc.fruits&gt;
619 &lt;ul&gt;
620 <emphasis> &lt;#items as fruit&gt;</emphasis>
621 &lt;li&gt;${fruit}
622 <emphasis> &lt;/#items&gt;</emphasis>
623 &lt;/ul&gt;
624 &lt;/#list&gt;</programlisting>
625
626 <para>Here, the <literal>list</literal> directive represents the
627 listing as a whole, and only the part inside the
628 <literal>items</literal> directive is repeated for each fruit. If
629 we have 0 fruits, everything inside <literal>list</literal> is
630 skipped, hence we will not have <literal>ul</literal> tags in
631 case.</para>
632
633 <para>Another frequent listing-related task: let's list the fruits
634 separating them with something, like a comma:</para>
635
636 <programlisting role="template">&lt;p&gt;Fruits: &lt;#list misc.fruits as fruit&gt;${fruit}<emphasis>&lt;#sep&gt;, </emphasis>&lt;/#list&gt;</programlisting>
637
638 <programlisting role="output">&lt;p&gt;Fruits: orange, banana</programlisting>
639
640 <para>The section covered by <literal>sep</literal> (which we
641 could be written like this too:
642 <literal><replaceable>...</replaceable>&lt;#sep&gt;,
643 &lt;/#sep&gt;&lt;/#list&gt;</literal>) will be only executed when
644 there will be a next item. Hence there's no comma after the last
645 fruit.</para>
646
647 <para>Here again, what if we have 0 fruits? Just printing
648 <quote>Fruits:</quote> and then nothing is awkward. A
649 <literal>list</literal>, just like an <literal>if</literal>, can
650 have an <literal>else</literal>, which is executed if there were 0
651 list items:</para>
652
653 <programlisting role="template">&lt;p&gt;Fruits: &lt;#list misc.fruits as fruit&gt;${fruit}&lt;#sep&gt;, <emphasis>&lt;#else&gt;None</emphasis>&lt;/#list&gt;</programlisting>
654
655 <note>
656 <para>As a matter of fact, this simplistic example could be
657 written like this, but it uses language devices that are off
658 topic here:</para>
659
660 <programlisting role="template">&lt;p&gt;Fruits: ${fruits?join(", ", "None")}</programlisting>
661 </note>
662
663 <para>All these directives (<literal>list</literal>,
664 <literal>items</literal>, <literal>sep</literal>,
665 <literal>else</literal>) can be used together:</para>
666
667 <programlisting role="template">&lt;#list misc.fruits&gt;
668 &lt;p&gt;Fruits:
669 &lt;ul&gt;
670 &lt;#items as fruit&gt;
671 &lt;li&gt;${fruit}&lt;#sep&gt; and&lt;/#sep&gt;
672 &lt;/#items&gt;
673 &lt;/ul&gt;
674 &lt;#else&gt;
675 &lt;p&gt;We have no fruits.
676 &lt;/#list&gt;</programlisting>
677
678 <note>
679 <para>You can read more about these directives <link
680 linkend="ref_directive_list">in the Reference</link>.</para>
681 </note>
682 </section>
683
684 <section>
685 <title>The include directive</title>
686
687 <para>With the <literal>include</literal> directive you can insert
688 the content of another file into the template.</para>
689
690 <para>Suppose you have to show the same copyright notice on
691 several pages. You can create a file that contains the copyright
692 notice only, and insert that file everywhere where you need that
693 copyright notice. Say, you store this copyright notice in
694 <literal>copyright_footer.html</literal>:</para>
695
696 <programlisting role="template">&lt;hr&gt;
697 &lt;i&gt;
698 Copyright (c) 2000 &lt;a href="http://www.acmee.com"&gt;Acmee Inc&lt;/a&gt;,
699 &lt;br&gt;
700 All Rights Reserved.
701 &lt;/i&gt;</programlisting>
702
703 <para>Whenever you need that file you simply insert it with the
704 <literal>include</literal> directive:</para>
705
706 <programlisting role="template">&lt;html&gt;
707 &lt;head&gt;
708 &lt;title&gt;Test page&lt;/title&gt;
709 &lt;/head&gt;
710 &lt;body&gt;
711 &lt;h1&gt;Test page&lt;/h1&gt;
712 &lt;p&gt;Blah blah...
713 <emphasis> &lt;#include "/copyright_footer.html"&gt;</emphasis>
714 &lt;/body&gt;
715 &lt;/html&gt;</programlisting>
716
717 <para>and the output will be:</para>
718
719 <programlisting role="output">&lt;html&gt;
720 &lt;head&gt;
721 &lt;title&gt;Test page&lt;/title&gt;
722 &lt;/head&gt;
723 &lt;body&gt;
724 &lt;h1&gt;Test page&lt;/h1&gt;
725 &lt;p&gt;Blah blah...
726 <emphasis>&lt;hr&gt;
727 &lt;i&gt;
728 Copyright (c) 2000 &lt;a href="http://www.acmee.com"&gt;Acmee Inc&lt;/a&gt;,
729 &lt;br&gt;
730 All Rights Reserved.
731 &lt;/i&gt;</emphasis>
732 &lt;/body&gt;
733 &lt;/html&gt;</programlisting>
734
735 <para>If you change the <literal>copyright_footer.html</literal>,
736 then the visitor will see the new copyright notice on all
737 pages.</para>
738
739 <note>
740 <para>A much more powerful way of reusing snippets is using
741 macros, but that's an advanced topic <link
742 linkend="dgui_misc_userdefdir">discussed later</link>.</para>
743 </note>
744 </section>
745 </section>
746
747 <section>
748 <title>Using directives together</title>
749
750 <para>You can use directives as many times on a page as you want,
751 and you can nest directives into each other freely. For example,
752 here you nest <literal>if</literal> directive inside a
753 <literal>list</literal> directive:</para>
754
755 <programlisting role="template"><emphasis>&lt;#list animals as animal&gt;</emphasis>
756 &lt;div<emphasis>&lt;#if animal.protected&gt;</emphasis><emphasis> </emphasis>class="protected"<emphasis>&lt;/#if&gt;</emphasis>&gt;
757 ${animal.name} for ${animal.price} Euros
758 &lt;/div&gt;
759 <emphasis>&lt;/#list&gt;</emphasis></programlisting>
760
761 <para>Note that since FreeMarker does not interpret text outside FTL
762 tags, interpolations and FTL comments, above you could use the FTL
763 tags inside HTML attributes without problem.</para>
764 </section>
765
766 <section>
767 <title>Using built-ins</title>
768
769 <para>The so-called built-ins are like subvariables (or rather like
770 methods, if you know that Java term) that aren't coming from the
771 data-model, but added by FreeMarker to the values. In order to make
772 it clear where subvariables comes from, you have to use
773 <literal>?</literal> (question mark) instead of <literal>.</literal>
774 (dot) to access them. <anchor
775 xml:id="topic.commonlyUsedBuiltIns"/>Examples with some of the most
776 commonly used built-ins:</para>
777
778 <itemizedlist>
779 <listitem>
780 <para><literal>user?upper_case</literal> gives the upper case
781 version of the value of <literal>user</literal> (like
782 <quote>JOHN DOE</quote> instead of <quote>John
783 Doe</quote>)</para>
784 </listitem>
785
786 <listitem>
787 <para><literal>animal.name?cap_first</literal> give the
788 <literal>animal.name</literal> with its first letter converted
789 to upper case (like <quote>Mouse</quote> instead of
790 <quote>mouse</quote>)</para>
791 </listitem>
792
793 <listitem>
794 <para><literal>user?length</literal> gives the number of
795 <emphasis>characters</emphasis> in the value of
796 <literal>user</literal> (8 for <quote>John Doe</quote>)</para>
797 </listitem>
798
799 <listitem>
800 <para><literal>animals?size</literal> gives the number of
801 <emphasis>items</emphasis> in the <literal>animals</literal>
802 sequence (3 in our example data-model)</para>
803 </listitem>
804
805 <listitem>
806 <para>If you are between <literal>&lt;#list animals as
807 animal&gt;</literal> and the corresponding
808 <literal>&lt;/#list&gt;</literal> tag:</para>
809
810 <itemizedlist>
811 <listitem>
812 <para><literal>animal?index</literal> gives the 0-based
813 index of <literal>animal</literal> inside
814 <literal>animals</literal></para>
815 </listitem>
816
817 <listitem>
818 <para><literal>animal?counter</literal> is like
819 <literal>index</literal>, but gives the 1-based index</para>
820 </listitem>
821
822 <listitem>
823 <para><literal>animal?item_parity</literal> gives the
824 strings <quote>odd</quote> or <quote>even</quote>, depending
825 on the current counter parity. This is commonly used for
826 coloring rows with alternating colors, like in
827 <literal>&lt;td
828 class="${animal?item_parity}Row"&gt;</literal>.</para>
829 </listitem>
830 </itemizedlist>
831 </listitem>
832 </itemizedlist>
833
834 <para>Some built-ins require parameters to specify the behavior
835 more, for example:</para>
836
837 <itemizedlist>
838 <listitem>
839 <para><literal>animal.protected?string("Y", "N")</literal>
840 return the string <quote>Y</quote> or <quote>N</quote> depending
841 on the boolean value of
842 <literal>animal.protected</literal>.</para>
843 </listitem>
844
845 <listitem>
846 <para><literal>animal?item_cycle('lightRow',
847 'darkRow')</literal> is the more generic variant of
848 <literal>item_parity</literal> from earlier.</para>
849 </listitem>
850
851 <listitem>
852 <para><literal>fruits?join(", ")</literal>: converts the list to
853 a string by concatenating items, and inserting the parameter
854 separator between each items (like <quote>orange,
855 banana</quote>)</para>
856 </listitem>
857
858 <listitem>
859 <para><literal>user?starts_with("J")</literal> gives boolean
860 true of false depending on if <literal>user</literal> starts
861 with the letter <quote>J</quote> or not.</para>
862 </listitem>
863 </itemizedlist>
864
865 <para>Built-in applications can be chained, like
866 <literal>fruits?join(", ")?upper_case</literal> will first convert
867 the list a to a string, then converts it to upper case. (This is
868 just like you can chain <literal>.</literal>-s (dots) too.)</para>
869
870 <para>You can find the <link linkend="ref_builtins">full set of
871 built-ins in the Reference</link>.</para>
872 </section>
873
874 <section>
875 <title>Dealing with missing variables</title>
876
877 <para>The data-model often has variables that are optional (i.e.,
878 sometimes missing). To spot some typical human mistakes, FreeMarker
879 doesn't tolerate references to missing variables unless you tell
880 explicitly what to do if the variable is missing. Here we will show
881 the two most typical ways of doing that.</para>
882
883 <para><phrase role="forProgrammers">Note for programmers: A
884 non-existent variable and a variable with <literal>null</literal>
885 value is the same for FreeMarker. The "missing" term used here
886 covers both cases.</phrase></para>
887
888 <para>Wherever you refer to a variable, you can specify a default
889 value for the case the variable is missing by following the variable
890 name with a <literal>!</literal> and the default value. Like in the
891 following example, when <literal>user</literal> is missing from data
892 model, the template will behave like if <literal>user</literal>'s
893 value were the string <literal>"visitor"</literal>. (When
894 <literal>user</literal> isn't missing, this template behaves exactly
895 like with <literal>${user}</literal>):</para>
896
897 <programlisting role="template">&lt;h1&gt;Welcome ${user<emphasis>!"visitor"</emphasis>}!&lt;/h1&gt;</programlisting>
898
899 <para>You can ask whether a variable isn't missing by putting
900 <literal>??</literal> after its name. Combining this with the
901 already introduced <literal>if</literal> directive you can skip the
902 whole greeting if the <literal>user</literal> variable is
903 missing:</para>
904
905 <programlisting role="template">&lt;#if <emphasis>user??</emphasis>&gt;&lt;h1&gt;Welcome ${user}!&lt;/h1&gt;&lt;/#if&gt;</programlisting>
906
907 <para>Regarding variable accessing with multiple steps, like
908 <literal>animals.python.price</literal>, writing
909 <literal>animals.python.price!0</literal> is correct only if
910 <literal>animals.python</literal> is never missing and only the last
911 subvariable, <literal>price</literal>, is possibly missing (in which
912 case here we assume it's <literal>0</literal>). If
913 <literal>animals</literal> or <literal>python</literal> is missing,
914 the template processing will stop with an "undefined variable"
915 error. To prevent that, you have to write
916 <literal>(animals.python.price)!0</literal>. In that case the
917 expression will be <literal>0</literal> even if
918 <literal>animals</literal> or <literal>python</literal> is missing.
919 Same logic goes for <literal>??</literal>;
920 <literal>animals.python.price??</literal> versus
921 <literal>(animals.python.price)??</literal>.</para>
922 </section>
923
924 <section xml:id="dgui_quickstart_template_autoescaping">
925 <title>Escaping for HTML, XML and other markup</title>
926
927 <para>Let's say the template generates HTML, and you insert values
928 with <literal>${<replaceable>...</replaceable>}</literal> that are
929 plain text (not HTML), like company names coming from a database.
930 Characters that has special meaning in HTML must be
931 <emphasis>escaped</emphasis> in such values, like if
932 <literal>name</literal> is <quote>Someone &amp; Co.</quote> then
933 <literal>${name}</literal> should print <quote>Someone
934 <emphasis>&amp;amp;</emphasis> Co.</quote>.</para>
935
936 <para>FreeMarker automatically escapes all values printed with
937 <literal>${<replaceable>...</replaceable>}</literal> <emphasis>if
938 it's properly configured</emphasis> (that's the responsibility of
939 the programmers; <link
940 linkend="pgui_config_outputformatsautoesc">see here how</link>). The
941 recommended practice is using <literal>ftlh</literal> file extension
942 to activate HTML auto-escaping, and <literal>ftlx</literal> file
943 extension to activate XML auto-escaping.</para>
944
945 <para>You can try if auto-escaping is on like
946 <literal>${"&lt;"}</literal> and then checking the raw output (for
947 HTML or XML escaping). If it's not, and the configuration won't be
948 adjusted, add this as the very first line of the template:</para>
949
950 <programlisting role="template">&lt;#ftl output_format="HTML"&gt;</programlisting>
951
952 <para>(Use <literal>"XML"</literal> instead of
953 <literal>"HTML"</literal> above if you generate XML.)</para>
954
955 <para>If the string value to print deliberately contains markup,
956 auto-escaping must be prevented like
957 <literal>${<replaceable>value</replaceable>?no_esc}</literal>.</para>
958
959 <para>You can find out much more about auto-escaping and output
960 formats <link linkend="dgui_misc_autoescaping">here...</link></para>
961
962 <note>
963 <para>The kind of automatic escaping described here requires at
964 least FreeMarker 2.3.24. If you have to use an earlier version,
965 use the deprecated <link
966 linkend="ref_directive_escape"><literal>escape</literal>
967 directive</link> instead.</para>
968 </note>
969 </section>
970 </section>
971 </chapter>
972
973 <chapter xml:id="dgui_datamodel">
974 <title>Values, Types</title>
975
976 <section xml:id="dgui_datamodel_basics">
977 <title>Basics</title>
978
979 <note>
980 <para>It is assumed that you have already read the <xref
981 linkend="dgui_quickstart"/> chapter.</para>
982 </note>
983
984 <para>Understanding the concept of values and types is crucial for the
985 understanding of data-models. However, the concept of values and types
986 is not confined to data-models, as you will see.</para>
987
988 <section xml:id="topic.value">
989 <title>What is a value?</title>
990
991 <indexterm>
992 <primary>value</primary>
993 </indexterm>
994
995 <para><phrase role="forProgrammers">Real programmers can safely skip
996 this section.</phrase></para>
997
998 <para>Examples of <emphasis>values</emphasis> as you know the term
999 from the everyday math are 16, 0.5, and so on, i.e. numbers. In the
1000 case of computer languages the value term has a wider meaning, as a
1001 value needn't be a number. For example, take this data-model:</para>
1002
1003 <programlisting role="dataModel" xml:id="example.stdDataModel">(root)
1004 |
1005 +- user = "Big Joe"
1006 |
1007 +- today = Jul 6, 2007
1008 |
1009 +- todayHoliday = false
1010 |
1011 +- lotteryNumbers
1012 | |
1013 | +- (1st) = 20
1014 | |
1015 | +- (2nd) = 14
1016 | |
1017 | +- (3rd) = 42
1018 | |
1019 | +- (4th) = 8
1020 | |
1021 | +- (5th) = 15
1022 |
1023 +- cargo
1024 |
1025 +- name = "coal"
1026 |
1027 +- weight = 40
1028 </programlisting>
1029
1030 <para>We say that the <emphasis>value</emphasis> of the the
1031 <literal>user</literal> variable is "Big Joe" (a string), the
1032 <emphasis>value</emphasis> of <literal>today</literal> is Jul 6,
1033 2007 (a date), the <emphasis>value</emphasis> of
1034 <literal>todayHoliday</literal> is false (a boolean, ie. a yes/no
1035 thing). The <emphasis>value</emphasis> of
1036 <literal>lotteryNumbers</literal> is the sequence that contains 20,
1037 14, 42, 8, 15. Surely <literal>lotteryNumbers</literal> is multiple
1038 values in the sense that it <emphasis>contains</emphasis> multiple
1039 values (for example, the 2nd item in it is a the
1040 <emphasis>value</emphasis> 14), but still,
1041 <literal>lotteryNumbers</literal> itself is a single value. It's
1042 like a box that contains many other items; the whole box can be seen
1043 as a single item. Last not least we also have the
1044 <emphasis>value</emphasis> of <literal>cargo</literal>, which is a
1045 hash (a box-like thing again).So, a value is something that can be
1046 stored in a variable (e.g., in <literal>user</literal> or
1047 <literal>cargo</literal> or <literal>cargo.name</literal>). But a
1048 value need not be stored in a variable to be called a value, for
1049 example we have the value 100 here:</para>
1050
1051 <programlisting role="template">&lt;#if cargo.weight &lt; <emphasis>100</emphasis>&gt;Light cargo&lt;/#if&gt;</programlisting>
1052
1053 <para>The temporaly result of a calculations are also called values,
1054 like 20 and 120 when this template is executed (it will print
1055 120):</para>
1056
1057 <programlisting role="template">${cargo.weight / 2 + 100}</programlisting>
1058
1059 <para>Explanation for this last: As the result of dividing the two
1060 values, 40 (the weight of the cargo) and 2, a new value 20 is
1061 created. Then 100 is added to it, so the value 120 is created. Then
1062 120 is printed
1063 (<literal>${<replaceable>...</replaceable>}</literal>), and the
1064 template execution goes on and all these values gone.</para>
1065
1066 <para>Certainly now you feel what the value term means.</para>
1067 </section>
1068
1069 <section>
1070 <title>What is type?</title>
1071
1072 <para>Values have an important aspect, their type. For example the
1073 type of the value of the <literal>user</literal> variable is string,
1074 and the type of the value of the <literal>lotteryNumbers</literal>
1075 variable is sequence. The type of a value is important because it
1076 determines to a large extent how and where you can use the value.
1077 Like <literal>${user / 2}</literal> is an error, but
1078 <literal>${cargo.weight / 2}</literal> works and prints 20, since
1079 division only does make sense for a number, but not for a string.
1080 Or, using dot like in <literal>cargo.name</literal> does make sense
1081 only if <literal>cargo</literal> is a hash. Or, you can list with
1082 <literal>&lt;#list <replaceable>...</replaceable>&gt;</literal>
1083 sequences only. Or, the condition of <literal>&lt;#if
1084 ...&gt;</literal> must be a boolean. And so on.</para>
1085
1086 <note>
1087 <para>A little terminology... Saying "a boolean" or "a boolean
1088 value" or "a value of type boolean" are all the same.</para>
1089 </note>
1090
1091 <para xml:id="topic.multitype"><indexterm>
1092 <primary>Multi-typed value</primary>
1093 </indexterm>A value can have multiple types at the same time,
1094 although it's rarely utilized. For example in the data-model below
1095 <literal>mouse</literal> is both a string and a hash:</para>
1096
1097 <programlisting role="dataModel">(root)
1098 |
1099 +- mouse = "Yerri"
1100 |
1101 +- age = 12
1102 |
1103 +- color = "brown"</programlisting>
1104
1105 <para>If you merge this template with the above data-model:</para>
1106
1107 <programlisting role="template">${mouse} &lt;#-- uses mouse as a string --&gt;
1108 ${mouse.age} &lt;#-- uses mouse as a hash --&gt;
1109 ${mouse.color} &lt;#-- uses mouse as a hash --&gt;</programlisting>
1110
1111 <para>the output will be:</para>
1112
1113 <programlisting role="output">Yerri
1114 12
1115 brown</programlisting>
1116 </section>
1117
1118 <section>
1119 <title>The data-model is a hash</title>
1120
1121 <para>Looking at the various data-model examples you may already
1122 realized: the thing marked as "(root)" is just a value of type hash.
1123 When you write something like <literal>user</literal>, that means
1124 that you want the "user" variable stored in the root hash. Like if
1125 you were writing <literal>root.user</literal>, except that there is
1126 no variable called "root" so that wouldn't work.</para>
1127
1128 <para>Some may get confused by the fact that our example data-model,
1129 that is, the root hash, contains further hashes and sequences
1130 (<literal>lotteryNumbers</literal> and <literal>cargo</literal>).
1131 There is nothing special in that. A hash contains other variables,
1132 and those variables have a value, which can be a string, a number,
1133 etc., and of course it can be a hash or sequence as well. Because,
1134 as it was explained earlier, a sequence or a hash is just a value,
1135 like a string or a number is.</para>
1136 </section>
1137 </section>
1138
1139 <section xml:id="dgui_datamodel_types">
1140 <title>The types</title>
1141
1142 <para>The suppored types are:</para>
1143
1144 <itemizedlist spacing="compact">
1145 <listitem>
1146 <para><link linkend="dgui_datamodel_scalar"
1147 os="">Scalars:</link></para>
1148
1149 <itemizedlist spacing="compact">
1150 <listitem>
1151 <para>String</para>
1152 </listitem>
1153
1154 <listitem>
1155 <para>Number</para>
1156 </listitem>
1157
1158 <listitem>
1159 <para>Boolean</para>
1160 </listitem>
1161
1162 <listitem>
1163 <para>Date-like (date, time, or date-time)</para>
1164 </listitem>
1165 </itemizedlist>
1166 </listitem>
1167
1168 <listitem>
1169 <para><link
1170 linkend="dgui_datamodel_container">Containers:</link></para>
1171
1172 <itemizedlist spacing="compact">
1173 <listitem>
1174 <para>Hash</para>
1175 </listitem>
1176
1177 <listitem>
1178 <para>Sequence</para>
1179 </listitem>
1180
1181 <listitem>
1182 <para>Collection</para>
1183 </listitem>
1184 </itemizedlist>
1185 </listitem>
1186
1187 <listitem>
1188 <para>Subroutines:</para>
1189
1190 <itemizedlist spacing="compact">
1191 <listitem>
1192 <para><link linkend="dgui_datamodel_method">Methods and
1193 functions</link></para>
1194 </listitem>
1195
1196 <listitem>
1197 <para><link linkend="dgui_datamodel_userdefdir">User-defined
1198 directives</link></para>
1199 </listitem>
1200 </itemizedlist>
1201 </listitem>
1202
1203 <listitem>
1204 <para>Miscellaneous/seldom used:</para>
1205
1206 <itemizedlist spacing="compact">
1207 <listitem>
1208 <para><link linkend="dgui_datamodel_node">Node</link></para>
1209 </listitem>
1210
1211 <listitem>
1212 <para><link linkend="dgui_datamodel_markupoutput">Markup
1213 output</link></para>
1214 </listitem>
1215 </itemizedlist>
1216 </listitem>
1217 </itemizedlist>
1218
1219 <section xml:id="dgui_datamodel_scalar">
1220 <title>Scalars</title>
1221
1222 <anchor xml:id="topic.designer.scalarVariable"/>
1223
1224 <para>These are the basic, simple kind of values. They can
1225 be:</para>
1226
1227 <itemizedlist>
1228 <listitem>
1229 <para><indexterm>
1230 <primary>string</primary>
1231
1232 <secondary>the FTL value type</secondary>
1233 </indexterm>String: It is simple text, e.g., the name of a
1234 product.</para>
1235
1236 <para>If you want to give a string value directly in the
1237 template, rather than use a variable that comes from the data
1238 model, you write the text between quotation marks, e.g.,
1239 <literal>"green mouse"</literal> or <literal>'green
1240 mouse'</literal>. (More details regarding the syntax can be
1241 found <link linkend="dgui_template_exp_direct_string"
1242 xml:lang="">later</link>.)</para>
1243 </listitem>
1244
1245 <listitem>
1246 <para><indexterm>
1247 <primary>number</primary>
1248
1249 <secondary>the FTL value type</secondary>
1250 </indexterm>Number: For example the price of a product.
1251 <phrase role="forProgrammers">Whole numbers and non-whole
1252 numbers are not distinguished; there is only a single number
1253 type. So for example 3/2 will be always 1.5, and never 1. Just
1254 like if you are using a calculator.</phrase></para>
1255
1256 <para>If you want to give a numerical value directly in the
1257 template, then you write for example: <literal>150</literal> or
1258 <literal>-90.05</literal> or <literal>0.001</literal>. (More
1259 details regarding the syntax can be found <link
1260 linkend="dgui_template_exp_direct_number"
1261 xml:lang="">later</link>.)</para>
1262 </listitem>
1263
1264 <listitem>
1265 <para><indexterm>
1266 <primary>boolean</primary>
1267
1268 <secondary>the FTL value type</secondary>
1269 </indexterm>Boolean: A boolean value represents a logical true
1270 or false (yes or no). For example, if a the visitor has been
1271 logged in or not. Typically you use booleans as the condition of
1272 the <literal>if</literal> directive, like <literal>&lt;#if
1273 loggedIn
1274 &gt;<replaceable>...</replaceable>&lt;/#if&gt;</literal> or
1275 <literal>&lt;#if price ==
1276 0&gt;<replaceable>...</replaceable>&lt;/#if&gt;</literal>; in
1277 the last case the result of the <literal>price == 0</literal>
1278 part is a boolean value.</para>
1279
1280 <para>In the templates you can directly specify a boolean with
1281 the reserved words <literal>true</literal> and
1282 <literal>false</literal>.</para>
1283 </listitem>
1284
1285 <listitem>
1286 <para><indexterm>
1287 <primary>date</primary>
1288
1289 <secondary>the FTL value type</secondary>
1290 </indexterm><indexterm>
1291 <primary>time</primary>
1292
1293 <secondary>the FTL value type</secondary>
1294 </indexterm><indexterm>
1295 <primary>date-time</primary>
1296
1297 <secondary>the FTL value type</secondary>
1298 </indexterm>Date: A date-like value stores date/time related
1299 data. It has three variations:</para>
1300
1301 <itemizedlist>
1302 <listitem>
1303 <para>Date: Like April 4, 2003. Day precision, no time of
1304 day part.</para>
1305 </listitem>
1306
1307 <listitem>
1308 <para>Time: Like 10:19:18 PM. Millisecond precision, no date
1309 part.</para>
1310 </listitem>
1311
1312 <listitem>
1313 <para>Date-time (sometimes called "time stamp") as April 4,
1314 2003 10:19:18 PM. Both date and time, with millisecond
1315 precision.</para>
1316 </listitem>
1317 </itemizedlist>
1318
1319 <para>Unfortunately, because of the limitations of the Java
1320 platform, FreeMarker sometimes can't decide which parts of the
1321 date are in use (i.e., if it is date-time, a date or a time).
1322 The solution for this problem is an advanced topic that will be
1323 discussed <link
1324 linkend="ref_builtin_date_datetype">later</link>.</para>
1325
1326 <para>It is possible to define date-like values directly in
1327 templates, but this is an advanced topic that will be explained
1328 <link linkend="ref_builtin_string_date">later</link>.</para>
1329 </listitem>
1330 </itemizedlist>
1331
1332 <para>Bear in mind that FreeMarker distinguishes strings from
1333 numbers, booleans and date-like values. For example, while the
1334 string <literal>"150"</literal> looks like the number
1335 <literal>150</literal>, a string is still just arbitrary sequence of
1336 characters, and you can't do arithmetic with it, can't compare it
1337 with another number, etc.</para>
1338 </section>
1339
1340 <section xml:id="dgui_datamodel_container">
1341 <title>Containers</title>
1342
1343 <remark>Re-explanation of hashes and sequences from a more
1344 ''professional'' viewpoint as earlier, and some meditation about
1345 them.</remark>
1346
1347 <para>These are the values whose purpose is to contain other
1348 variables; they are just containers. The contained variables are
1349 often referred as <emphasis>sub variables</emphasis>. The container
1350 types are:</para>
1351
1352 <itemizedlist>
1353 <listitem>
1354 <para><indexterm>
1355 <primary>hash</primary>
1356
1357 <secondary>the FTL value type</secondary>
1358 </indexterm>Hash: Associates a unique lookup name with each of
1359 its sub variables. The name is an unrestricted string. A hash
1360 <emphasis>doesn't define an ordering</emphasis> for the sub
1361 variables in it. That is, there is no such thing as the first
1362 subvariable, and the second subvariable, etc.; the variables are
1363 just accessed by name.</para>
1364 </listitem>
1365
1366 <listitem>
1367 <para><indexterm>
1368 <primary>sequence</primary>
1369
1370 <secondary>the FTL value type</secondary>
1371 </indexterm>Sequence: Associates an integer number with each
1372 of its sub variables. The first subvariable is associated with
1373 0, the second with 1, the third to 2, and so on; the sub
1374 variables are ordered. These numbers are often called the
1375 <emphasis>indexes</emphasis> of the sub variables. Sequences are
1376 usually dense, i.e., all indexes up to the index of the last
1377 subvariable have an associated subvariable, but it's not
1378 strictly necessary. The type of the subvariable values need not
1379 be the same.</para>
1380 </listitem>
1381
1382 <listitem>
1383 <para><indexterm>
1384 <primary>collection</primary>
1385
1386 <secondary>the FTL value type</secondary>
1387 </indexterm>Collection: A collection, from the viewpoint of
1388 the template author, is a restricted sequence. You cannot access
1389 its size or retrieve its sub variables by index, but they can be
1390 still listed with the <link
1391 linkend="ref.directive.list"><literal>list</literal>
1392 directive</link>.</para>
1393 </listitem>
1394 </itemizedlist>
1395
1396 <para>Note that since <link linkend="topic.multitype">a value can
1397 have multiple types</link>, it is possible for a value to be both a
1398 hash and a sequence, in which case it would support index-based
1399 access as well as access by lookup name. However, typically a
1400 container will be either a hash or a sequence, not both.</para>
1401
1402 <para>As the value of the variables stored in hashes and sequences
1403 (and collections) can be anything, it can be a hash or sequence (or
1404 collection) as well. This way you can build arbitrarily deep
1405 structures.</para>
1406
1407 <para>The data-model itself (or better said the root of it) is a
1408 hash.</para>
1409
1410 <para>FreeMarker templates don't support modifying the contents of
1411 containers (such as adding, removing or replacing sub variables),
1412 and it assumes that their content won't change during template
1413 processing. (But you can make new container values by adding
1414 together two existing container values with <literal>+</literal>;
1415 see that in the <link linkend="exp_cheatsheet">chapter about
1416 expressions</link>, and please note the performance
1417 consequences.)</para>
1418 </section>
1419
1420 <section>
1421 <title>Subroutines</title>
1422
1423 <section xml:id="dgui_datamodel_method">
1424 <title>Methods and functions</title>
1425
1426 <anchor xml:id="topic.designer.methodVariable"/>
1427
1428 <indexterm>
1429 <primary>method</primary>
1430
1431 <secondary>the FTL value type</secondary>
1432 </indexterm>
1433
1434 <para>A value that is a method or a function is used to calculate
1435 another value, influenced by the parameters you give to it.</para>
1436
1437 <para><phrase role="forProgrammers">For programmer types:
1438 Methods/functions are first-class values, just like in functional
1439 programming languages. This means that functions/methods can be
1440 the parameters or return values of other functions/methods, you
1441 can assign them to variables, and so on.</phrase></para>
1442
1443 <para>Suppose that programmers have put the method variable
1444 <literal>avg</literal> in the data-model that can be used to
1445 calculate the average of numbers. If you give the 3 and 5 as
1446 parameters when you access <literal>avg</literal>, then you get
1447 the value 4.</para>
1448
1449 <para>The usage of methods will be explained <link
1450 linkend="dgui_template_exp_methodcall">later</link>, but perhaps
1451 this example helps to understand what methods are:</para>
1452
1453 <programlisting role="template">The average of 3 and 5 is: ${avg(3, 5)}
1454 The average of 6 and 10 and 20 is: ${avg(6, 10, 20)}
1455 The average of the price of a python and an elephant is:
1456 ${avg(animals.python.price, animals.elephant.price)}</programlisting>
1457
1458 <para>this will output:</para>
1459
1460 <programlisting role="output">The average of 3 and 5 is: 4
1461 The average of 6 and 10 and 20 is: 12
1462 The average of the price of a python and an elephant is:
1463 4999.5</programlisting>
1464
1465 <para>What is the difference between a method and a function? As
1466 far as the template author is concerned, nothing. Well not really
1467 nothing, as methods typically come from the data-model (<phrase
1468 role="forProgrammers">as they reflect the methods of Java
1469 objects</phrase>), and functions are defined in templates (with
1470 the <link
1471 linkend="ref.directive.function"><literal>function</literal>
1472 directive</link> -- an advanced topic), but both can be used on
1473 the same way.</para>
1474 </section>
1475
1476 <section xml:id="dgui_datamodel_userdefdir">
1477 <title>User-defined directives</title>
1478
1479 <indexterm>
1480 <primary>macro</primary>
1481
1482 <secondary>the FTL value type</secondary>
1483 </indexterm>
1484
1485 <indexterm>
1486 <primary>directive</primary>
1487
1488 <secondary>the FTL value type</secondary>
1489 </indexterm>
1490
1491 <indexterm>
1492 <primary>user-defined directive</primary>
1493
1494 <secondary>the FTL value type</secondary>
1495 </indexterm>
1496
1497 <para>A value of this type can be used as user-defined directive
1498 (with other words, as FreeMarker tag). An user-defined directive
1499 is a subroutine, something like a little reusable template
1500 fragment. But this is an advanced topic that will be explained
1501 <link linkend="dgui_misc_userdefdir">later</link> in its own
1502 chapter.</para>
1503
1504 <para><phrase role="forProgrammers">For programmer types:
1505 user-defined directives (such as macros), are first-class values
1506 too, just like functions/methods are.</phrase></para>
1507
1508 <para>Just to get an idea about user-defined directives (so just
1509 ignore this if you won't understand), assume we have a variable,
1510 <literal>box</literal>, whose value is a user-defined directive
1511 that prints some kind of fancy HTML message box with a title bar
1512 and a message in it. The <literal>box</literal> variable could be
1513 used in the template like this (for example):</para>
1514
1515 <programlisting role="template">&lt;@<emphasis>box</emphasis> title="Attention!"&gt;
1516 Too much copy-pasting may leads to
1517 maintenance headaches.
1518 &lt;/@<emphasis>box</emphasis>&gt;</programlisting>
1519 </section>
1520
1521 <section>
1522 <title>Function/method versus user-defined directive</title>
1523
1524 <para>This is for advanced users again (so ignore it if you don't
1525 understand). It's a frequent dilemma if you should use a
1526 function/method or an user-defined directive to implement
1527 something. The rule of thumb is: Implement the facility as
1528 user-defined directive instead of as function/method if:</para>
1529
1530 <itemizedlist>
1531 <listitem>
1532 <para>... the purpose of it is generating a piece of the
1533 output that's not just a single value, and typically involves
1534 markup. The template language was designed for printing to the
1535 output directly, piece by piece, as it goes though
1536 <literal>list</literal> loops, <literal>if</literal>-s, etc.
1537 Building up a string value in a variable then returning it is
1538 much less convenient.</para>
1539 </listitem>
1540
1541 <listitem>
1542 <para>... it's the side-effect that is important and not the
1543 return value. For example, a directive whose purpose is to add
1544 an entry to the server log is like that. (In fact you can't
1545 have a return value for a user-defined directive, but some
1546 kind of feedback is still possible by setting non-local
1547 variables.)</para>
1548 </listitem>
1549
1550 <listitem>
1551 <para>... it will do flow control on the caller side (like for
1552 example <literal>list</literal> or <literal>if</literal>
1553 directives do). You just can't do that with a
1554 function/method.</para>
1555 </listitem>
1556
1557 <listitem>
1558 <para>... you are using legacy escaping via the
1559 <literal>escape</literal> directive (instead of <link
1560 linkend="dgui_misc_autoescaping">auto-escaping</link>), and
1561 the result contains markup. When you print the result with
1562 <literal>${<replaceable>...</replaceable>}</literal>, the
1563 markup will be escaped and thus ruined, but if it's printed by
1564 a directive call
1565 (<literal>&lt;@<replaceable>...</replaceable>&gt;</literal>),
1566 it won't be.</para>
1567 </listitem>
1568 </itemizedlist>
1569
1570 <para>The Java methods of FreeMarker-unaware Java objects are
1571 normally visible as methods in templates, regardless of the nature
1572 of the Java method; you have no choice there.</para>
1573 </section>
1574 </section>
1575
1576 <section>
1577 <title>Miscellaneous</title>
1578
1579 <section xml:id="dgui_datamodel_node">
1580 <title>Nodes</title>
1581
1582 <indexterm>
1583 <primary>node</primary>
1584
1585 <secondary>the FTL value type</secondary>
1586 </indexterm>
1587
1588 <para>Node variables represent a node in a tree structure, and are
1589 used mostly with <link linkend="xgui">XML processing</link>, which
1590 is an advanced, and specialized topic.</para>
1591
1592 <para>Still, a quick overview <emphasis>for advanced
1593 users</emphasis>: A node is similar to a sequence that stores
1594 other nodes, which are often referred as the children nodes. A
1595 node stores a reference to its container node, which is often
1596 referred as the parent node. The main point of being a node is the
1597 topological information; other data must be stored by utilizing
1598 that a value can have multiple types. Like, a value may be both a
1599 node and a number, in which case it can store a number as the
1600 "pay-load". Apart from the topological information, a node can
1601 store some metainformation as well: a node name, a node type
1602 (string), and a node namespace (string). For example, if the node
1603 symbolizes a <literal>h1</literal> element in an XHTML document,
1604 then its name could be <literal>"h1"</literal>, it's node type
1605 could be <literal>"element"</literal>, and it's namespace could be
1606 <literal>"http://www.w3.org/1999/xhtml"</literal>. But it's up to
1607 the designer of the data-model if what meaning these
1608 metainformations have, and if they are used at all. The way of
1609 retrieving the topological and metainformations is described <link
1610 linkend="ref_builtins_node">in a later chapter</link> (that you
1611 don't have to understand at this point).</para>
1612 </section>
1613
1614 <section xml:id="dgui_datamodel_markupoutput">
1615 <title>Markup output</title>
1616
1617 <indexterm>
1618 <primary>markup output</primary>
1619
1620 <secondary>the FTL value type</secondary>
1621 </indexterm>
1622
1623 <para>This type is related to <link
1624 linkend="dgui_misc_autoescaping">auto-escaping mechanism</link>
1625 introduced FreeMarker 2.3.24; you can <link
1626 linkend="dgui_misc_autoescaping_movalues">read about this type
1627 there</link>. But in short, this is a value that stores text
1628 that's already in the output markup format (like HTML, XML, RTF,
1629 etc.), and hence must not be auto-escaped.</para>
1630
1631 <para>Values of this type are usually produced inside the
1632 templates (like with <link
1633 linkend="ref_builtin_no_esc"><literal>no_esc</literal>
1634 built-in</link> or <link linkend="ref_directive_assign">output
1635 capturing assignments</link>), but can also be part of the
1636 data-model. Such values in the data-model are useful for example
1637 if you have message resources that sometimes contain the message
1638 in HTML format, rather than in plain text. If the data-model uses
1639 HTML markup output values for those messages instead of strings,
1640 then the template author need not know which messages contain HTML
1641 and which plain text, as double escaping will be avoided
1642 automatically when the message is inserted with
1643 <literal>${<replaceable>...</replaceable>}</literal>.</para>
1644 </section>
1645 </section>
1646 </section>
1647 </chapter>
1648
1649 <chapter xml:id="dgui_template">
1650 <title>The Template</title>
1651
1652 <indexterm>
1653 <primary>template</primary>
1654 </indexterm>
1655
1656 <note>
1657 <para>It is assumed that you have already read the <xref
1658 linkend="dgui_quickstart"/> and the <xref linkend="dgui_datamodel"/>
1659 chapter.</para>
1660 </note>
1661
1662 <section xml:id="dgui_template_overallstructure">
1663 <title>Overall structure</title>
1664
1665 <para>Templates are in fact programs you write in a language called
1666 <indexterm>
1667 <primary>FTL</primary>
1668 </indexterm><emphasis role="term">FTL</emphasis> (for FreeMarker
1669 Template Language). This is a quite simple programming language
1670 designed for writing templates and nothing else.</para>
1671
1672 <para>A template (= FTL program) is a mix of the following
1673 sections:</para>
1674
1675 <itemizedlist>
1676 <listitem>
1677 <para><emphasis role="term">Text</emphasis><indexterm>
1678 <primary>text</primary>
1679 </indexterm>: Text that will be printed to the output as
1680 is.</para>
1681 </listitem>
1682
1683 <listitem>
1684 <para><emphasis role="term">Interpolation</emphasis><indexterm>
1685 <primary>interpolation</primary>
1686 </indexterm>: These sections will be replaced with a calculated
1687 value in the output. Interpolations are delimited by
1688 <literal>${</literal> and <literal>}</literal> (or with
1689 <literal>#{</literal> and <literal>}</literal>, but that shouldn't
1690 be used anymore; <link
1691 linkend="ref_depr_numerical_interpolation">see more
1692 here</link>).</para>
1693 </listitem>
1694
1695 <listitem>
1696 <para><emphasis role="term">FTL tags</emphasis><indexterm>
1697 <primary>FTL tag</primary>
1698 </indexterm>: FTL tags are a bit similar to HTML tags, but they
1699 are instructions to FreeMarker and will not be printed to the
1700 output.</para>
1701 </listitem>
1702
1703 <listitem>
1704 <para><emphasis role="term">Comments</emphasis><indexterm>
1705 <primary>comment</primary>
1706 </indexterm><indexterm>
1707 <primary>&lt;#--...--&gt;</primary>
1708 </indexterm><indexterm>
1709 <primary>#</primary>
1710 </indexterm>: Comments are similar to HTML comments, but they
1711 are delimited by <literal>&lt;#--</literal> and
1712 <literal>--&gt;</literal>. Comments will be ignored by FreeMarker,
1713 and will not be written to the output.</para>
1714 </listitem>
1715 </itemizedlist>
1716
1717 <para>Let's see a concrete template. I have marked the template's
1718 components with colors: <phrase role="markedText">text</phrase>,
1719 <phrase role="markedInterpolation">interpolation</phrase>, <phrase
1720 role="markedFTLTag">FTL tag</phrase>, <phrase
1721 role="markedComment">comment</phrase>. With the <phrase
1722 role="markedInvisibleText">[BR]</phrase>-s I intend to visualize the
1723 <link linkend="gloss.lineBreak">line breaks</link>.</para>
1724
1725 <programlisting role="template"><phrase role="markedText">&lt;html&gt;<phrase
1726 role="markedInvisibleText">[BR]</phrase>
1727 &lt;head&gt;<phrase role="markedInvisibleText">[BR]</phrase>
1728   &lt;title&gt;Welcome!&lt;/title&gt;<phrase role="markedInvisibleText">[BR]</phrase>
1729 &lt;/head&gt;<phrase role="markedInvisibleText">[BR]</phrase>
1730 &lt;body&gt;<phrase role="markedInvisibleText">[BR]</phrase>
1731   <phrase role="markedComment">&lt;#-- Greet the user with his/her name --&gt;</phrase><phrase
1732 role="markedInvisibleText">[BR]</phrase>
1733   &lt;h1&gt;Welcome <phrase role="markedInterpolation">${user}</phrase>!&lt;/h1&gt;<phrase
1734 role="markedInvisibleText">[BR]</phrase>
1735   &lt;p&gt;We have these animals:<phrase role="markedInvisibleText">[BR]</phrase>
1736   &lt;ul&gt;<phrase role="markedInvisibleText">[BR]</phrase>
1737   <phrase role="markedFTLTag">&lt;#list animals as animal&gt;</phrase><phrase
1738 role="markedInvisibleText">[BR]</phrase>
1739     &lt;li&gt;<phrase role="markedInterpolation">${animal.name}</phrase> for <phrase
1740 role="markedInterpolation">${animal.price}</phrase> Euros<phrase
1741 role="markedInvisibleText">[BR]</phrase>
1742   <phrase role="markedFTLTag">&lt;/#list&gt;</phrase><phrase
1743 role="markedInvisibleText">[BR]</phrase>
1744   &lt;/ul&gt;<phrase role="markedInvisibleText">[BR]</phrase>
1745 &lt;/body&gt;<phrase role="markedInvisibleText">[BR]</phrase>
1746 &lt;/html&gt;</phrase></programlisting>
1747
1748 <para>FTL distinguishes upper case and lower case letters. So
1749 <literal>list</literal> is good directive name, while
1750 <literal>List</literal> is not. Similarly <literal>${name}</literal>
1751 is not the same as <literal>${Name}</literal> or
1752 <literal>${NAME}</literal></para>
1753
1754 <para>It is important to realize that <phrase
1755 role="markedInterpolation">interpolations</phrase> can be used in
1756 <phrase role="markedText">text</phrase> (and in string literal
1757 expressions; see <link
1758 linkend="dgui_template_exp_stringop_interpolation">later</link>)
1759 only.</para>
1760
1761 <para>An <phrase role="markedFTLTag">FTL tag</phrase> can't be inside
1762 another <phrase role="markedFTLTag">FTL tag</phrase> nor inside an
1763 <phrase role="markedInterpolation">interpolation</phrase>. For example
1764 this is <emphasis>WRONG</emphasis>: <literal>&lt;#if &lt;#include
1765 'foo'&gt;='bar'&gt;...&lt;/#if&gt;</literal></para>
1766
1767 <para><phrase role="markedComment">Comments</phrase> can be placed
1768 inside <phrase role="markedFTLTag">FTL tags</phrase> and <phrase
1769 role="markedInterpolation">interpolations</phrase>. For
1770 example:</para>
1771
1772 <programlisting role="template"><phrase role="markedText">&lt;h1&gt;Welcome <phrase
1773 role="markedInterpolation">${user <phrase role="markedComment">&lt;#-- The name of user --&gt;</phrase>}</phrase>!&lt;/h1&gt;<phrase
1774 role="markedInvisibleText">[BR]</phrase>
1775 &lt;p&gt;We have these animals:<phrase role="markedInvisibleText">[BR]</phrase>
1776 &lt;ul&gt;<phrase role="markedInvisibleText">[BR]</phrase>
1777 <phrase role="markedFTLTag">&lt;#list <phrase role="markedComment">&lt;#-- some comment... --&gt;</phrase> animals as <phrase
1778 role="markedComment">&lt;#-- again... --&gt;</phrase> animal&gt;</phrase><phrase
1779 role="markedInvisibleText">[BR]</phrase></phrase>
1780 <replaceable>...</replaceable></programlisting>
1781
1782 <note>
1783 <para>For those of you who have tried the above examples: You may
1784 notice that some of spaces, tabs and line breaks are missing from
1785 the template output, even though we said that <phrase
1786 role="markedText">text</phrase> is printed as is. Don't bother with
1787 it now. This is because the feature called ''white-space stripping''
1788 is turned on, and that automatically removes some superfluous
1789 spaces, tabs and line breaks. This will be explained <link
1790 linkend="dgui_misc_whitespace">later</link>.</para>
1791 </note>
1792 </section>
1793
1794 <section xml:id="dgui_template_directives">
1795 <title>Directives</title>
1796
1797 <indexterm>
1798 <primary>&lt;#...&gt;</primary>
1799 </indexterm>
1800
1801 <indexterm>
1802 <primary>#</primary>
1803 </indexterm>
1804
1805 <anchor xml:id="term.designer.directive"/>
1806
1807 <remark>Note that the Expressions chapter depends on this chapter, and
1808 Interpolations chapter depends on Expressions chapter. Thus Directives
1809 must be the first chapter after Basics.</remark>
1810
1811 <para><indexterm>
1812 <primary>directive</primary>
1813 </indexterm>You use FTL tags to call <emphasis
1814 role="term">directives</emphasis>. In the example you have called the
1815 <literal>list</literal> directive. Syntactically you have done it with
1816 two tags: <literal>&lt;#list animals as animal&gt;</literal> and
1817 <literal>&lt;/#list&gt;</literal>.</para>
1818
1819 <para><indexterm>
1820 <primary>FTL tag</primary>
1821 </indexterm>There are two kind of FTL tags:</para>
1822
1823 <itemizedlist>
1824 <listitem>
1825 <para>Start-tag:
1826 <literal>&lt;#<replaceable>directivename</replaceable>
1827 <replaceable>parameters</replaceable>&gt;</literal></para>
1828 </listitem>
1829
1830 <listitem>
1831 <para>End-tag:
1832 <literal>&lt;/#<replaceable>directivename</replaceable>&gt;</literal></para>
1833 </listitem>
1834 </itemizedlist>
1835
1836 <para>This is similar to HTML or XML syntax, except that the tag name
1837 starts with <literal>#</literal>. If the directive doesn't have nested
1838 content (content between the start-tag and the end-tag), you must use
1839 the start-tag with no end-tag. For example you write <literal>&lt;#if
1840 <replaceable>something</replaceable>&gt;<replaceable>...</replaceable>&lt;/#if&gt;</literal>,
1841 but just <literal>&lt;#include
1842 <replaceable>something</replaceable>&gt;</literal> as FreeMarker knows
1843 that the <literal>include</literal> directive can't have nested
1844 content.</para>
1845
1846 <para>The format of the
1847 <literal><replaceable>parameters</replaceable></literal> depends on
1848 the
1849 <literal><replaceable>directivename</replaceable></literal>.</para>
1850
1851 <para>In fact there are two types of directives: <link
1852 linkend="gloss.predefinedDirective">predefined directives</link> and
1853 <link linkend="gloss.userDefinedDirective">user-defined
1854 directives</link>. For user-defined directives you use
1855 <literal>@</literal> instead of <literal>#</literal>, for example
1856 <literal>&lt;@mydirective
1857 <replaceable>parameters</replaceable>&gt;<replaceable>...</replaceable>&lt;/@mydirective&gt;</literal>.
1858 Further difference is that if the directive has no nested content, you
1859 must use a tag like <literal>&lt;@mydirective
1860 <replaceable>parameters</replaceable> /&gt;</literal>, similarly as in
1861 XML (e.g. <literal>&lt;img <replaceable>...</replaceable>
1862 /&gt;</literal>). But user-defined directives is an advanced topic
1863 that will be discussed <link
1864 linkend="dgui_misc_userdefdir">later</link>.</para>
1865
1866 <para>FTL tags, like HTML tags, must be properly nested. So the code
1867 below is wrong, as the <literal>if</literal> directive is both inside
1868 and outside of the nested content of the <literal>list</literal>
1869 directive:</para>
1870
1871 <programlisting role="template">&lt;ul&gt;
1872 <emphasis>&lt;#list animals as animal&gt;</emphasis>
1873 &lt;li&gt;${animal.name} for ${animal.price} Euros
1874 <emphasis>&lt;#if user == "Big Joe"&gt;</emphasis>
1875 (except for you)
1876 <emphasis>&lt;/#list&gt;</emphasis> &lt;#-- WRONG! The "if" has to be closed first. --&gt;
1877 <emphasis>&lt;/#if&gt;</emphasis>
1878 &lt;/ul&gt;</programlisting>
1879
1880 <para>Note that FreeMarker doesn't care about the nesting of HTML
1881 tags, only about the nesting of FTL tags. It just sees HTML as flat
1882 text, it doesn't interpret it in any way.</para>
1883
1884 <para>If you try to use a non-existing directive (e.g., you mistype
1885 the directive name), FreeMarker will decline to use the template and
1886 produce an error message.</para>
1887
1888 <para>FreeMarker ignores superfluous <link
1889 linkend="gloss.whiteSpace">white-space</link> inside FTL tags. So you
1890 can write this:</para>
1891
1892 <programlisting role="template"><phrase role="markedText"><phrase
1893 role="markedFTLTag">&lt;#list<phrase role="markedInvisibleText">[BR]</phrase>
1894   animals       as<phrase role="markedInvisibleText">[BR]</phrase>
1895      animal<phrase role="markedInvisibleText">[BR]</phrase>
1896 &gt;</phrase><phrase role="markedInvisibleText">[BR]</phrase>
1897 <phrase role="markedInterpolation">${animal.name}</phrase> for <phrase
1898 role="markedInterpolation">${animal.price}</phrase> Euros<phrase
1899 role="markedInvisibleText">[BR]</phrase>
1900 <phrase role="markedFTLTag">&lt;/#list    &gt;</phrase></phrase></programlisting>
1901
1902 <para>You may not, however, insert white-space between the
1903 <literal>&lt;</literal> or <literal>&lt;/</literal> and the directive
1904 name.</para>
1905
1906 <para>The complete list and description of all directives can be found
1907 in the <xref linkend="ref_directives"/> (but I recommend that you look
1908 at the chapter about expressions first).</para>
1909
1910 <note>
1911 <para>FreeMarker can be configured to use <literal>[</literal> and
1912 <literal>]</literal> instead of <literal>&lt;</literal> and
1913 <literal>&gt;</literal> in the FTL tags and FTL comments, like
1914 <literal>[#if user == "Big
1915 Joe"]<replaceable>...</replaceable>[/#if]</literal>. For more
1916 information read: <xref
1917 linkend="dgui_misc_alternativesyntax"/>.</para>
1918 </note>
1919
1920 <note>
1921 <para>FreeMarker can be configured so that it understands predefined
1922 directives without <literal>#</literal> (like <literal>&lt;if user
1923 == "Big
1924 Joe"&gt;<replaceable>...</replaceable>&lt;/if&gt;</literal>).
1925 However we don't recommend the usage of this mode. For more
1926 information read: <xref linkend="ref_depr_oldsyntax"/></para>
1927 </note>
1928 </section>
1929
1930 <section xml:id="dgui_template_exp">
1931 <title>Expressions</title>
1932
1933 <para><indexterm>
1934 <primary>expression</primary>
1935 </indexterm>When you supply values for interpolations or directive
1936 parameters you can use variables or more complex expressions. For
1937 example, if x is the number 8 and y is 5, the value of <literal>(x +
1938 y)/2</literal> resolves to the numerical value 6.5.</para>
1939
1940 <para>Before we go into details, let's see some concrete
1941 examples:</para>
1942
1943 <itemizedlist>
1944 <listitem>
1945 <para>When you supply value for interpolations: The usage of
1946 interpolations is
1947 <literal>${<replaceable>expression</replaceable>}</literal> where
1948 expression gives the value you want to insert into the output as
1949 text. So <literal>${(5 + 8)/2}</literal> prints <quote>6.5</quote>
1950 to the output (or possibly <quote>6,5</quote> if the language of
1951 your output is not US English).</para>
1952 </listitem>
1953
1954 <listitem>
1955 <para>When you supply a value for the directive parameter: You
1956 have already seen the <literal>if</literal> directive in the
1957 Getting Started section. The syntax of this directive is:
1958 <literal>&lt;#if
1959 <replaceable>expression</replaceable>&gt;<replaceable>...</replaceable>&lt;/#if&gt;</literal>.
1960 The expression here must evaluate to a boolean value. For example
1961 in <literal>&lt;#if 2 &lt; 3&gt;</literal> the <literal>2 &lt;
1962 3</literal> (2 is less than 3) is an expression which evaluates to
1963 <literal>true</literal>.</para>
1964 </listitem>
1965 </itemizedlist>
1966
1967 <section xml:id="exp_cheatsheet">
1968 <title>Quick overview (cheat sheet)</title>
1969
1970 <para>This is a reminder for those of you who already know
1971 FreeMarker or are just experienced programmers:</para>
1972
1973 <itemizedlist spacing="compact">
1974 <listitem>
1975 <para><link linkend="dgui_template_exp_direct">Specify values
1976 directly</link></para>
1977
1978 <itemizedlist spacing="compact">
1979 <listitem>
1980 <para><link
1981 linkend="dgui_template_exp_direct_string">Strings</link>:
1982 <literal>"Foo"</literal> or <literal>'Foo'</literal> or
1983 <literal>"It's \"quoted\""</literal> or <literal>'It\'s
1984 "quoted"'</literal> or
1985 <literal>r"C:\raw\string"</literal></para>
1986 </listitem>
1987
1988 <listitem>
1989 <para><link
1990 linkend="dgui_template_exp_direct_number">Numbers</link>:
1991 <literal>123.45</literal></para>
1992 </listitem>
1993
1994 <listitem>
1995 <para><link
1996 linkend="dgui_template_exp_direct_boolean">Booleans</link>:
1997 <literal>true</literal>, <literal>false</literal></para>
1998 </listitem>
1999
2000 <listitem>
2001 <para><link
2002 linkend="dgui_template_exp_direct_seuqence">Sequences</link>:
2003 <literal>["foo", "bar", 123.45]</literal>; Ranges:
2004 <literal>0..9</literal>, <literal>0..&lt;10</literal> (or
2005 <literal>0..!10</literal>), <literal>0..</literal></para>
2006 </listitem>
2007
2008 <listitem>
2009 <para><link
2010 linkend="dgui_template_exp_direct_hash">Hashes</link>:
2011 <literal>{"name":"green mouse",
2012 "price":150}</literal></para>
2013 </listitem>
2014 </itemizedlist>
2015 </listitem>
2016
2017 <listitem>
2018 <para><link linkend="dgui_template_exp_var">Retrieving
2019 variables</link></para>
2020
2021 <itemizedlist spacing="compact">
2022 <listitem>
2023 <para><link
2024 linkend="dgui_template_exp_var_toplevel">Top-level
2025 variables</link>: <literal>user</literal></para>
2026 </listitem>
2027
2028 <listitem>
2029 <para><link linkend="dgui_template_exp_var_hash">Retrieving
2030 data from a hash</link>: <literal>user.name</literal>,
2031 <literal>user["name"]</literal></para>
2032 </listitem>
2033
2034 <listitem>
2035 <para><link
2036 linkend="dgui_template_exp_var_sequence">Retrieving data
2037 from a sequence</link>:
2038 <literal>products[5]</literal></para>
2039 </listitem>
2040
2041 <listitem>
2042 <para><link linkend="dgui_template_exp_var_special">Special
2043 variable</link>: <literal>.main</literal></para>
2044 </listitem>
2045 </itemizedlist>
2046 </listitem>
2047
2048 <listitem>
2049 <para><link linkend="dgui_template_exp_stringop">String
2050 operations</link></para>
2051
2052 <itemizedlist spacing="compact">
2053 <listitem>
2054 <para><link
2055 linkend="dgui_template_exp_stringop_interpolation">Interpolation
2056 and concatenation</link>:
2057 <literal>"Hello ${user}!"</literal> (or <literal>"Hello
2058 " + user + "!"</literal>)</para>
2059 </listitem>
2060
2061 <listitem>
2062 <para><link
2063 linkend="dgui_template_exp_get_character">Getting a
2064 character</link>: <literal>name[0]</literal></para>
2065 </listitem>
2066
2067 <listitem>
2068 <para><link
2069 linkend="dgui_template_exp_stringop_slice">String
2070 slice:</link> Inclusive end: <literal>name[0..4]</literal>,
2071 Exclusive end: <literal>name[0..&lt;5]</literal>,
2072 Length-based (lenient): <literal>name[0..*5]</literal>,
2073 Remove starting: <literal>name[5..]</literal></para>
2074 </listitem>
2075 </itemizedlist>
2076 </listitem>
2077
2078 <listitem>
2079 <para><link linkend="dgui_template_exp_sequenceop">Sequence
2080 operations</link></para>
2081
2082 <itemizedlist spacing="compact">
2083 <listitem>
2084 <para><link
2085 linkend="dgui_template_exp_sequenceop_cat">Concatenation</link>:
2086 <literal>users + ["guest"]</literal></para>
2087 </listitem>
2088
2089 <listitem>
2090 <para><link
2091 linkend="dgui_template_exp_seqenceop_slice">Sequence
2092 slice</link>: Inclusive end:
2093 <literal>products[20..29]</literal>, Exclusive end:
2094 <literal>products[20..&lt;30]</literal>, Length-based
2095 (lenient): <literal>products[20..*10]</literal>, Remove
2096 starting: <literal>products[20..]</literal></para>
2097 </listitem>
2098 </itemizedlist>
2099 </listitem>
2100
2101 <listitem>
2102 <para><link linkend="dgui_template_exp_hashop">Hash
2103 operations</link></para>
2104
2105 <itemizedlist spacing="compact">
2106 <listitem>
2107 <para><link
2108 linkend="dgui_template_exp_hashop_cat">Concatenation</link>:
2109 <literal>passwords + { "joe": "secret42" }</literal></para>
2110 </listitem>
2111 </itemizedlist>
2112 </listitem>
2113
2114 <listitem>
2115 <para><link linkend="dgui_template_exp_arit">Arithmetical
2116 calculations</link>: <literal>(x * 1.5 + 10) / 2 - y %
2117 100</literal></para>
2118 </listitem>
2119
2120 <listitem>
2121 <para><link
2122 linkend="dgui_template_exp_comparison">Comparison</link>:
2123 <literal>x == y</literal>, <literal>x != y</literal>,
2124 <literal>&lt; y</literal>, <literal>&gt; y</literal>,
2125 <literal>&gt;= y</literal>, <literal>&lt;= y</literal>,
2126 <literal>x lt y</literal>, <literal>x lte y</literal>,
2127 <literal>x gt y</literal>, <literal>x gte y</literal>,
2128 ...etc.</para>
2129 </listitem>
2130
2131 <listitem>
2132 <para><link linkend="dgui_template_exp_logicalop">Logical
2133 operations</link>: <literal>!registered &amp;&amp; (firstVisit
2134 || fromEurope)</literal></para>
2135 </listitem>
2136
2137 <listitem>
2138 <para><link
2139 linkend="dgui_template_exp_builtin">Built-ins</link>:
2140 <literal>name?upper_case</literal>,
2141 <literal>path?ensure_starts_with('/')</literal></para>
2142 </listitem>
2143
2144 <listitem>
2145 <para><link linkend="dgui_template_exp_methodcall">Method
2146 call</link>: <literal>repeat("What", 3)</literal></para>
2147 </listitem>
2148
2149 <listitem>
2150 <para><link linkend="dgui_template_exp_missing">Missing value
2151 handler operators</link>:</para>
2152
2153 <itemizedlist spacing="compact">
2154 <listitem>
2155 <para><link
2156 linkend="dgui_template_exp_missing_default">Default
2157 value</link>: <literal>name!"unknown"</literal> or
2158 <literal>(user.name)!"unknown"</literal> or
2159 <literal>name!</literal> or
2160 <literal>(user.name)!</literal></para>
2161 </listitem>
2162
2163 <listitem>
2164 <para><link linkend="dgui_template_exp_missing_test">Missing
2165 value test</link>: <literal>name??</literal> or
2166 <literal>(user.name)??</literal></para>
2167 </listitem>
2168 </itemizedlist>
2169 </listitem>
2170
2171 <listitem>
2172 <para><link linkend="dgui_template_exp_assignment">Assignment
2173 operators</link>: <literal>=</literal>, <literal>+=</literal>,
2174 <literal>-=</literal>, <literal>*=</literal>,
2175 <literal>/=</literal>, <literal>%=</literal>,
2176 <literal>++</literal>, <literal>--</literal></para>
2177 </listitem>
2178 </itemizedlist>
2179
2180 <para>See also: <link
2181 linkend="dgui_template_exp_precedence">Operator
2182 precedence</link></para>
2183 </section>
2184
2185 <section xml:id="dgui_template_exp_direct">
2186 <title>Specify values directly</title>
2187
2188 <indexterm>
2189 <primary>literal</primary>
2190 </indexterm>
2191
2192 <indexterm>
2193 <primary>constant</primary>
2194 </indexterm>
2195
2196 <para>Often you want to specify a value directly and not as a result
2197 of some calculations.</para>
2198
2199 <section xml:id="dgui_template_exp_direct_string">
2200 <title>Strings</title>
2201
2202 <indexterm>
2203 <primary>string</primary>
2204
2205 <secondary>literal</secondary>
2206 </indexterm>
2207
2208 <para>To specify a string value directly you give the text in
2209 quotation marks, e.g.: <literal>"some text"</literal> or in
2210 apostrophe-quote, e.g. <literal>'some text'</literal>. The two
2211 forms are equivalent. If the text itself contains the character
2212 used for the quoting (either <literal>"</literal> or
2213 <literal>'</literal>) or backslashes, you have to precede them
2214 with a backslash; this is called escaping. You can type any other
2215 character, including <link linkend="gloss.lineBreak">line
2216 breaks</link>, in the text directly. Example:</para>
2217
2218 <programlisting role="template">${"It's \"quoted\" and
2219 this is a backslash: \\"}
2220
2221 ${'It\'s "quoted" and
2222 this is a backslash: \\'}</programlisting>
2223
2224 <para>will print:</para>
2225
2226 <programlisting role="output">It's "quoted" and
2227 this is a backslash: \
2228
2229 It's "quoted" and
2230 this is a backslash: \</programlisting>
2231
2232 <note>
2233 <para>Of course, you could simply type the above text into the
2234 template, without using
2235 <literal>${<replaceable>...</replaceable>}</literal>. But we do
2236 it here just for the sake of example, to demonstrate
2237 expressions.</para>
2238 </note>
2239
2240 <anchor xml:id="topic.escapeSequence"/>
2241
2242 <indexterm>
2243 <primary>escape sequences</primary>
2244 </indexterm>
2245
2246 <para>This is the list of all supported escape sequences. All
2247 other usage of backlash in string literals is an error and any
2248 attempt to use the template will fail.</para>
2249
2250 <informaltable border="1">
2251 <thead>
2252 <tr>
2253 <th>Escape sequence</th>
2254
2255 <th>Meaning</th>
2256 </tr>
2257 </thead>
2258
2259 <tbody>
2260 <tr>
2261 <td><literal>\"</literal></td>
2262
2263 <td>Quotation mark (u0022)</td>
2264 </tr>
2265
2266 <tr>
2267 <td><literal>\'</literal></td>
2268
2269 <td>Apostrophe (a.k.a. apostrophe-quote) (u0027)</td>
2270 </tr>
2271
2272 <tr>
2273 <td><literal>\{</literal></td>
2274
2275 <td>Opening curly brace: <literal>{</literal></td>
2276 </tr>
2277
2278 <tr>
2279 <td><literal>\\</literal></td>
2280
2281 <td>Back slash (u005C)</td>
2282 </tr>
2283
2284 <tr>
2285 <td><literal>\n</literal></td>
2286
2287 <td>Line feed (u000A)</td>
2288 </tr>
2289
2290 <tr>
2291 <td><literal>\r</literal></td>
2292
2293 <td>Carriage return (u000D)</td>
2294 </tr>
2295
2296 <tr>
2297 <td><literal>\t</literal></td>
2298
2299 <td>Horizontal tabulation (a.k.a. tab) (u0009)</td>
2300 </tr>
2301
2302 <tr>
2303 <td><literal>\b</literal></td>
2304
2305 <td>Backspace (u0008)</td>
2306 </tr>
2307
2308 <tr>
2309 <td><literal>\f</literal></td>
2310
2311 <td>Form feed (u000C)</td>
2312 </tr>
2313
2314 <tr>
2315 <td><literal>\l</literal></td>
2316
2317 <td>Less-than sign: <literal>&lt;</literal></td>
2318 </tr>
2319
2320 <tr>
2321 <td><literal>\g</literal></td>
2322
2323 <td>Greater-than sign: <literal>&gt;</literal></td>
2324 </tr>
2325
2326 <tr>
2327 <td><literal>\a</literal></td>
2328
2329 <td>Ampersand: <literal>&amp;</literal></td>
2330 </tr>
2331
2332 <tr>
2333 <td><literal>\x<replaceable>Code</replaceable></literal></td>
2334
2335 <td>Character given with its hexadecimal <link
2336 linkend="gloss.unicode">Unicode</link> code (<link
2337 linkend="gloss.UCS">UCS</link> code)</td>
2338 </tr>
2339 </tbody>
2340 </informaltable>
2341
2342 <para>The <literal><replaceable>Code</replaceable></literal> after
2343 the <literal>\x</literal> is 1 to 4 hexadecimal digits. For
2344 example this all put a copyright sign into the string:
2345 <literal>"\xA9 1999-2001"</literal>,
2346 <literal>"\x0A9 1999-2001"</literal>,
2347 <literal>"\x00A9 1999-2001"</literal>. When the character directly
2348 after the last hexadecimal digit can be interpreted as hexadecimal
2349 digit, you must use all 4 digits or else FreeMarker will
2350 misunderstand you.</para>
2351
2352 <para>Note that the character sequence <literal>${</literal> (and
2353 <literal>#{</literal>) has special meaning. It's used to insert
2354 the value of expressions (typically: the value of variables, as in
2355 <literal>"Hello ${user}!"</literal>). This will be explained <link
2356 linkend="dgui_template_exp_stringop_interpolation">later</link>.
2357 If you want to print <literal>${</literal> or
2358 <literal>#{</literal>, you should either use raw string literals
2359 as explained below, or escape the <literal>{</literal> like in
2360 <literal>"foo $\{bar}"</literal>.</para>
2361
2362 <indexterm>
2363 <primary>raw string literal</primary>
2364 </indexterm>
2365
2366 <para>A special kind of string literals is the raw string
2367 literals. In raw string literals, backslash and
2368 <literal>${</literal> have no special meaning, they are considered
2369 as plain characters. To indicate that a string literal is a raw
2370 string literal, you have to put an <literal>r</literal> directly
2371 before the opening quotation mark or apostrophe-quote.
2372 Example:</para>
2373
2374 <programlisting role="template">${r"${foo}"}
2375 ${r"C:\foo\bar"}</programlisting>
2376
2377 <para>will print:</para>
2378
2379 <programlisting role="output">${foo}
2380 C:\foo\bar</programlisting>
2381 </section>
2382
2383 <section xml:id="dgui_template_exp_direct_number">
2384 <title>Numbers</title>
2385
2386 <indexterm>
2387 <primary>number</primary>
2388
2389 <secondary>literal</secondary>
2390 </indexterm>
2391
2392 <para>To specify a numerical value directly you type the number
2393 without quotation marks. You have to use the dot as your decimal
2394 separator and must not use any grouping separator symbols. You can
2395 use <literal>-</literal> or <literal>+</literal> to indicate the
2396 sign (<literal>+</literal> is redundant). Scientific notation is
2397 not yet supported (so <literal>1E3</literal> is wrong). Also, you
2398 cannot omit the 0 before the decimal separator (so
2399 <literal>.5</literal> is wrong).</para>
2400
2401 <para>Examples of valid number literals: <literal>0.08</literal>,
2402 <literal>-5.013</literal>, <literal>8</literal>,
2403 <literal>008</literal>, <literal>11</literal>,
2404 <literal>+11</literal></para>
2405
2406 <para>Note that numerical literals like <literal>08</literal>,
2407 <literal>+8</literal>, <literal>8.00</literal> and
2408 <literal>8</literal> are totally equivalent as they all symbolize
2409 the number eight. Thus, <literal>${08}</literal>,
2410 <literal>${+8}</literal>, <literal>${8.00}</literal> and
2411 <literal>${8}</literal> will all print exactly same.</para>
2412 </section>
2413
2414 <section xml:id="dgui_template_exp_direct_boolean">
2415 <title>Booleans</title>
2416
2417 <indexterm>
2418 <primary>boolean</primary>
2419
2420 <secondary>literal</secondary>
2421 </indexterm>
2422
2423 <indexterm>
2424 <primary>literal</primary>
2425
2426 <secondary>boolean</secondary>
2427 </indexterm>
2428
2429 <para>To specify a boolean value you write <literal>true</literal>
2430 or <literal>false</literal>. Don't use quotation marks.</para>
2431 </section>
2432
2433 <section xml:id="dgui_template_exp_direct_seuqence">
2434 <title>Sequences</title>
2435
2436 <indexterm>
2437 <primary>sequence</primary>
2438
2439 <secondary>literal</secondary>
2440 </indexterm>
2441
2442 <indexterm>
2443 <primary>numerical sequence</primary>
2444 </indexterm>
2445
2446 <indexterm>
2447 <primary>numerical range expression</primary>
2448 </indexterm>
2449
2450 <indexterm>
2451 <primary>range expression</primary>
2452 </indexterm>
2453
2454 <para>To specify a literal sequence, you list the <link
2455 linkend="topic.dataModel.subVar">sub variables</link> separated by
2456 commas, and put the whole list into square brackets. For
2457 example:</para>
2458
2459 <programlisting role="template">&lt;#list <emphasis>["foo", "bar", "baz"]</emphasis> as x&gt;
2460 ${x}
2461 &lt;/#list&gt;</programlisting>
2462
2463 <para>will print:</para>
2464
2465 <programlisting role="output">foo
2466 bar
2467 baz
2468 </programlisting>
2469
2470 <para>The items in the list are expressions, so you can do this
2471 for example: <literal>[2 + 2, [1, 2, 3, 4], "foo"]</literal>. Here
2472 the first subvariable will be the number 4, the second will be
2473 another sequence, and the third subvariable will be the string
2474 <quote>foo</quote>.</para>
2475 </section>
2476
2477 <section xml:id="dgui_template_exp_direct_ranges">
2478 <title>Ranges</title>
2479
2480 <para>Ranges are just sequences, but they are created by
2481 specifying what range of whole numbers they contain, instead of
2482 specifying their items one by one. For example,
2483 <literal>0..&lt;m</literal>, assuming the <literal>m</literal>
2484 variable stores 5, will give a sequence that contains <literal>[0,
2485 1, 2, 3, 4]</literal>. Ranges are primarily used for iterating
2486 over a range of numbers with <literal>&lt;#list
2487 <replaceable>...</replaceable>&gt;</literal> and for <link
2488 linkend="dgui_template_exp_seqenceop_slice">slicing
2489 sequences</link> and <link
2490 linkend="dgui_template_exp_stringop_slice">slicing
2491 strings</link>.</para>
2492
2493 <para>The generic forms of range expressions are (where
2494 <literal><replaceable>start</replaceable></literal> and
2495 <literal><replaceable>end</replaceable></literal> can be any
2496 expression that evaluates to a number):</para>
2497
2498 <itemizedlist>
2499 <listitem>
2500 <para><literal><replaceable>start</replaceable>..<replaceable>end</replaceable></literal>:
2501 Range with inclusive end. For example, <literal>1..4</literal>
2502 gives <literal>[1, 2, 3, 4]</literal>, and
2503 <literal>4..1</literal> gives <literal>[4, 3, 2, 1]</literal>.
2504 Beware, ranges with inclusive end never give an empty
2505 sequence, so <literal>0..length-1</literal> is
2506 <emphasis>WRONG</emphasis>, because when length is
2507 <literal>0</literal> it gives <literal>[0,
2508 -1]</literal>.</para>
2509 </listitem>
2510
2511 <listitem>
2512 <para><literal><replaceable>start</replaceable>..&lt;<replaceable>end</replaceable></literal>
2513 or
2514 <literal><replaceable>start</replaceable>..!<replaceable>end</replaceable></literal>:
2515 Range with exclusive end. For example,
2516 <literal>1..&lt;4</literal> gives <literal>[1, 2,
2517 3]</literal>, <literal>4..&lt;1</literal> gives <literal>[4,
2518 3, 2]</literal>, and <literal>1..&lt;1</literal> gives
2519 <literal>[]</literal>. Note the last example; the result can
2520 be an empty sequence. There's no difference between
2521 <literal>..&lt;</literal> and <literal>..!</literal>; the last
2522 form is used in applications where using the
2523 <literal>&lt;</literal> character causes problems (for HTML
2524 editors and such).</para>
2525 </listitem>
2526
2527 <listitem>
2528 <para><literal><replaceable>start</replaceable>..*<replaceable>length</replaceable></literal>:
2529 Length limited range. For example, <literal>10..*4</literal>
2530 gives <literal>[10, 11, 12, 13]</literal>,
2531 <literal>10..*-4</literal> gives <literal>[10, 9, 8,
2532 7]</literal>, and <literal>10..*0</literal> gives
2533 <literal>[]</literal>. When these kind of ranges are used for
2534 slicing, the slice will end without error if the end of the
2535 sliced sequence or string is reached before the specified
2536 range length was reached; see <link
2537 linkend="dgui_template_exp_seqenceop_slice">slicing
2538 sequences</link> for more.</para>
2539
2540 <note>
2541 <para>Length limited ranges were introduced in FreeMarker
2542 2.3.21.</para>
2543 </note>
2544 </listitem>
2545
2546 <listitem>
2547 <para><literal><replaceable>start</replaceable>..</literal>:
2548 Right-unbounded range. This are like length limited ranges
2549 with infinite length. For example <literal>1..</literal> gives
2550 <literal>[1, 2, 3, 4, 5, 6, ... ]</literal>, up to infinity.
2551 Be careful when processing (like listing) such ranges, as
2552 processing all items of it it would take forever or until the
2553 application runs out of memory and crashes. Just like with
2554 length limited ranges, when these kind of ranges are used for
2555 slicing, the slice will end when the end of the sliced
2556 sequence or string is reached.</para>
2557
2558 <warning>
2559 <para>Right-unbounded ranges before FreeMarker 2.3.21 were
2560 only used for slicing, and behaved like an empty sequence
2561 for other purposes. To activate the new behavior, it's not
2562 enough to use FreeMarker 2.3.21, the programmer also have to
2563 set the <literal>incompatible_improvements</literal>
2564 configuration setting to at least 2.3.21.</para>
2565 </warning>
2566 </listitem>
2567 </itemizedlist>
2568
2569 <para>Further notes on ranges:</para>
2570
2571 <itemizedlist>
2572 <listitem>
2573 <para>Range expressions themselves don't have square brackets,
2574 for example, you write <literal>&lt;#assign myRange =
2575 0..&lt;x</literal>, NOT <literal>&lt;#assign myRange =
2576 [0..&lt;x]&gt;</literal>. The last would create a sequence
2577 that contains an item that's a range. The square brackets are
2578 part of the slicing syntax, like
2579 <literal><replaceable>seq</replaceable>[<replaceable>myRange</replaceable>]</literal>.</para>
2580 </listitem>
2581
2582 <listitem>
2583 <para>You can write arithmetical expression on the sides of
2584 the <literal>..</literal> without parenthesis, like <literal>n
2585 + 1 ..&lt; m / 2 - 1</literal>.</para>
2586 </listitem>
2587
2588 <listitem>
2589 <para><literal>..</literal>, <literal>..&lt;</literal>,
2590 <literal>..!</literal> and <literal>..*</literal> are
2591 operators, so you can't have space inside them. Like
2592 <literal>n .. &lt;m</literal> is WRONG, but <literal>n ..&lt;
2593 m</literal> is good.</para>
2594 </listitem>
2595
2596 <listitem>
2597 <para>The reported size of right-unbounded ranges is
2598 2147483647 (or 0 if
2599 <literal>incompatible_improvements</literal> is less than
2600 2.3.21) due to a technical limitation (32 bits). However, when
2601 listing them, their actual size is infinite.</para>
2602 </listitem>
2603
2604 <listitem>
2605 <para>Ranges don't really store the numbers they consist of,
2606 thus for example <literal>0..1</literal> and
2607 <literal>0..100000000</literal> is equally fast to create and
2608 takes the same amount of memory.</para>
2609 </listitem>
2610 </itemizedlist>
2611 </section>
2612
2613 <section xml:id="dgui_template_exp_direct_hash">
2614 <title>Hashes</title>
2615
2616 <indexterm>
2617 <primary>hash</primary>
2618
2619 <secondary>literal</secondary>
2620 </indexterm>
2621
2622 <indexterm>
2623 <primary>literal</primary>
2624
2625 <secondary>hash</secondary>
2626 </indexterm>
2627
2628 <para>To specify a hash in a template, you list the key/value
2629 pairs separated by commas, and put the list into curly brackets.
2630 The key and value within a key/value pair are separated with a
2631 colon. Here is an example: <literal>{ "name": "green mouse",
2632 "price": 150 }</literal>. Note that both the names and the values
2633 are expressions. The keys must be strings. The values can be if
2634 any type.</para>
2635 </section>
2636 </section>
2637
2638 <section xml:id="dgui_template_exp_var">
2639 <title>Retrieving variables</title>
2640
2641 <section xml:id="dgui_template_exp_var_toplevel">
2642 <title>Top-level variables</title>
2643
2644 <indexterm>
2645 <primary>subvariable</primary>
2646
2647 <secondary>accessing</secondary>
2648 </indexterm>
2649
2650 <para>To access a top-level variable, you simply use the variable
2651 name. For example, the expression <literal>user</literal> will
2652 evaluate to the value of variable stored with name
2653 <quote>user</quote> in the root. So this will print what you store
2654 there:</para>
2655
2656 <programlisting role="template">${user}</programlisting>
2657
2658 <para>If there is no such top-level variable, then an error will
2659 result when FreeMarker tries to evaluate the expression, and it
2660 aborts template processing (unless programmers has configured
2661 FreeMarker differently).</para>
2662
2663 <para>In this kind of expression, the variable name can only
2664 contain letters (including non-Latin letters), digits (including
2665 non-Latin digits), underline (<literal>_</literal>), dollar
2666 (<literal>$</literal>), at sign (<literal>@</literal>).
2667 Furthermore, the first character can't be a ASCII digit
2668 (<literal>0</literal>-<literal>9</literal>). Starting from
2669 FreeMarker 2.3.22, the variable name can also contain minus
2670 (<literal>-</literal>), dot (<literal>.</literal>), and colon
2671 (<literal>:</literal>) at any position, but these must be escaped
2672 with a preceding backslash (<literal>\</literal>), or else they
2673 would be interpreted as operators. For example, to read the
2674 variable whose name is <quote>data-id</quote>, the expression is
2675 <literal>data\-id</literal>, as <literal>data-id</literal> would
2676 be interpreted as <quote>data minus id</quote>. (Note that these
2677 escapes only work in identifiers, not in string literals.)</para>
2678 </section>
2679
2680 <section xml:id="dgui_template_exp_var_hash">
2681 <title>Retrieving data from a hash</title>
2682
2683 <indexterm>
2684 <primary>subvariable</primary>
2685
2686 <secondary>accessing</secondary>
2687 </indexterm>
2688
2689 <indexterm>
2690 <primary>hash</primary>
2691
2692 <secondary>accessing subvariable</secondary>
2693 </indexterm>
2694
2695 <para>If we already have a hash as a result of an expression, then
2696 we can get its subvariable with a dot and the name of the
2697 subvariable. Assume that we have this data-model:</para>
2698
2699 <programlisting role="dataModel">(root)
2700 |
2701 +- book
2702 | |
2703 | +- title = "Breeding green mouses"
2704 | |
2705 | +- author
2706 | |
2707 | +- name = "Julia Smith"
2708 | |
2709 | +- info = "Biologist, 1923-1985, Canada"
2710 |
2711 +- test = "title"</programlisting>
2712
2713 <para>Now we can read the <literal>title</literal> with
2714 <literal>book.title</literal>, since the book expression will
2715 return a hash (as explained in the last chapter). Applying this
2716 logic further, we can read the name of the author with this
2717 expression: <literal>book.author.name</literal>.</para>
2718
2719 <para>There is an alternative syntax if we want to specify the
2720 subvariable name with an expression:
2721 <literal>book["title"]</literal>. In the square brackets you can
2722 give any expression as long as it evaluates to a string. So with
2723 this data-model you can also read the title with
2724 <literal>book[test]</literal>. More examples; these are all
2725 equivalent: <literal>book.author.name</literal>,
2726 <literal>book["author"].name</literal>,
2727 <literal>book.author["name"]</literal>,
2728 <literal>book["author"]["name"]</literal>.</para>
2729
2730 <para>When you use the dot syntax, the same restrictions apply
2731 regarding the variable name as with top-level variables (name can
2732 contain only letters, digits, <literal>_</literal>,
2733 <literal>$</literal>, <literal>@</literal> but can't start with
2734 <literal>0</literal>-<literal>9</literal>, also starting from
2735 2.3.22 you can also use <literal>\-</literal>,
2736 <literal>\.</literal> and <literal>\:</literal>). There are no
2737 such restrictions when you use the square bracket syntax, since
2738 the name is the result of an arbitrary expression. (Note, that to
2739 help the FreeMarker XML support, if the subvariable name is
2740 <literal>*</literal> (asterisk) or <literal>**</literal>, then you
2741 do not have to use square bracket syntax.)</para>
2742
2743 <para>As with the top-level variables, trying to access a
2744 non-existent subvariable causes an error and aborts the processing
2745 of the template (unless programmers has configured FreeMarker
2746 differently).</para>
2747 </section>
2748
2749 <section xml:id="dgui_template_exp_var_sequence">
2750 <title>Retrieving data from a sequence</title>
2751
2752 <indexterm>
2753 <primary>subvariable</primary>
2754
2755 <secondary>accessing</secondary>
2756 </indexterm>
2757
2758 <indexterm>
2759 <primary>sequence</primary>
2760
2761 <secondary>accessing subvariable</secondary>
2762 </indexterm>
2763
2764 <para>This is the same as for hashes, but you can use the square
2765 bracket syntax only, and the expression in the brackets must
2766 evaluate to a number, not a string. For example to get the name of
2767 the first animal of the <link
2768 linkend="example.stdDataModel">example data-model</link> (remember
2769 that the number of the first item is 0, not 1):
2770 <literal>animals[0].name</literal></para>
2771 </section>
2772
2773 <section xml:id="dgui_template_exp_var_special">
2774 <title>Special variables</title>
2775
2776 <indexterm>
2777 <primary>special variables</primary>
2778 </indexterm>
2779
2780 <para>Special variables are variables defined by the FreeMarker
2781 engine itself. To access them, you use the
2782 <literal>.<replaceable>variable_name</replaceable></literal>
2783 syntax.</para>
2784
2785 <para>Normally you don't need to use special variables. They are
2786 for expert users. The complete list of special variables can be
2787 found in the <link linkend="ref_specvar">reference</link>.</para>
2788 </section>
2789 </section>
2790
2791 <section xml:id="dgui_template_exp_stringop">
2792 <title>String operations</title>
2793
2794 <indexterm>
2795 <primary>string</primary>
2796
2797 <secondary>operations</secondary>
2798 </indexterm>
2799
2800 <section xml:id="dgui_template_exp_stringop_interpolation">
2801 <title>Interpolation and concatenation</title>
2802
2803 <indexterm>
2804 <primary>interpolation</primary>
2805 </indexterm>
2806
2807 <indexterm>
2808 <primary>concatenate strings</primary>
2809 </indexterm>
2810
2811 <indexterm>
2812 <primary>joining strings</primary>
2813 </indexterm>
2814
2815 <indexterm>
2816 <primary>string</primary>
2817
2818 <secondary>concatenate</secondary>
2819 </indexterm>
2820
2821 <indexterm>
2822 <primary>string</primary>
2823
2824 <secondary>interpolation</secondary>
2825 </indexterm>
2826
2827 <indexterm>
2828 <primary>adding strings</primary>
2829 </indexterm>
2830
2831 <para>If you want to insert the value of an expression into a
2832 string, you can use
2833 <literal>${<replaceable>...</replaceable>}</literal> (and the
2834 deprecated <literal>#{<replaceable>...</replaceable>}</literal>)
2835 in string literals.
2836 <literal>${<replaceable>...</replaceable>}</literal> in string
2837 literals <link linkend="dgui_template_valueinsertion">behaves
2838 similarly as in <phrase role="markedText">text</phrase>
2839 sections</link> (so it goes through the same <emphasis>locale
2840 sensitive</emphasis> number and date/time formatting).</para>
2841
2842 <para>Example (assume that user is <quote>Big Joe</quote>):</para>
2843
2844 <programlisting role="template">&lt;#assign s = "Hello ${user}!"&gt;
2845 ${s} &lt;#-- Just to see what the value of s is --&gt;
2846 </programlisting>
2847
2848 <para>This will print:</para>
2849
2850 <programlisting role="output">Hello Big Joe!</programlisting>
2851
2852 <warning>
2853 <para>A frequent mistake of users is the usage of interpolations
2854 in places where they needn't/shouldn't/can't be used.
2855 Interpolations work <emphasis>only</emphasis> in <link
2856 linkend="dgui_template_overallstructure"><phrase
2857 role="markedText">text</phrase> sections</link> (e.g.
2858 <literal>&lt;h1&gt;Hello ${name}!&lt;/h1&gt;</literal>) and in
2859 string literals (e.g. <literal>&lt;#include
2860 "/footer/${company}.html"&gt;</literal>). A typical
2861 <emphasis>WRONG</emphasis> usage is <literal>&lt;#if
2862 ${big}&gt;...&lt;/#if&gt;</literal>, which will cause a
2863 syntactical error. You should simply write <literal>&lt;#if
2864 big&gt;...&lt;/#if&gt;</literal>. Also, <literal>&lt;#if
2865 "${big}"&gt;...&lt;/#if&gt;</literal> is
2866 <emphasis>WRONG</emphasis>, since it converts the parameter
2867 value to string and the <literal>if</literal> directive wants a
2868 boolean value, so it will cause a runtime error.</para>
2869 </warning>
2870
2871 <para
2872 xml:id="dgui_template_exp_stringop_concatenation">Alternatively,
2873 you can use the <literal>+</literal> operator to achieve similar
2874 result:</para>
2875
2876 <programlisting role="template">&lt;#assign s = "Hello " + user + "!"&gt;</programlisting>
2877
2878 <para>This gives the same result as the earlier example with the
2879 <literal>${<replaceable>...</replaceable>}</literal>.</para>
2880
2881 <warning>
2882 <para>Because <literal>+</literal> follows similar rules as
2883 <literal>${<replaceable>...</replaceable>}</literal>, the
2884 appended string is influenced by the <literal>locale</literal>,
2885 <literal>number_format</literal>,
2886 <literal>date_format</literal>, <literal>time_format</literal>,
2887 <literal>datetime_format</literal> and
2888 <literal>boolean_format</literal>, etc. settings, and thus the
2889 result targets humans and isn't in generally machine parseable.
2890 This mostly leads to problems with numbers, as many locales use
2891 grouping (thousands separators) by default, and so
2892 <literal>"someUrl?id=" + id</literal> becomes to something like
2893 <literal>"someUrl?id=1 234"</literal>. To prevent this, use the
2894 <literal>?c</literal> (for Computer audience) built-in, like in
2895 <literal>"someUrl?id=" + id?c</literal> or
2896 <literal>"someUrl?id=${id?c}"</literal>, which will evaluate to
2897 something like <literal>"someUrl?id=1234"</literal>, regardless
2898 of locale and format settings.</para>
2899 </warning>
2900
2901 <para>As when <literal>${<replaceable>...</replaceable>}</literal>
2902 is used inside string <emphasis>expressions</emphasis> it's just a
2903 shorthand of using the <literal>+</literal> operator, <link
2904 linkend="dgui_misc_autoescaping">auto-escaping</link> is not
2905 applied on it.</para>
2906 </section>
2907
2908 <section xml:id="dgui_template_exp_get_character">
2909 <title>Getting a character</title>
2910
2911 <indexterm>
2912 <primary>charAt</primary>
2913 </indexterm>
2914
2915 <indexterm>
2916 <primary>get character</primary>
2917 </indexterm>
2918
2919 <para>You can get a single character of a string at a given index
2920 similarly as you can <link
2921 linkend="dgui_template_exp_var_sequence">read the subvariable of a
2922 sequence</link>, e.g. <literal>user[0]</literal>. The result will
2923 be a string whose length is 1; FTL doesn't have a separate
2924 character type. As with sequence sub variables, the index must be
2925 a number that is at least 0 and less than the length of the
2926 string, or else an error will abort the template
2927 processing.</para>
2928
2929 <para>Since the sequence subvariable syntax and the character
2930 getter syntax clashes, you can use the character getter syntax
2931 only if the variable is not a sequence as well (which is possible
2932 because FTL supports multi-typed values), since in that case the
2933 sequence behavior prevails. (To work this around, you can use
2934 <link linkend="ref_builtin_string_for_string">the
2935 <literal>string</literal> built-in</link>, e.g.
2936 <literal>user?string[0]</literal>. Don't worry if you don't
2937 understand this yet; built-ins will be discussed later.)</para>
2938
2939 <para>Example (assume that user is <quote>Big Joe</quote>):</para>
2940
2941 <programlisting role="template">${user[0]}
2942 ${user[4]}</programlisting>
2943
2944 <para>will print (note that the index of the first character is
2945 0):</para>
2946
2947 <programlisting role="output">B
2948 J</programlisting>
2949 </section>
2950
2951 <section xml:id="dgui_template_exp_stringop_slice">
2952 <title>String slicing (substrings)</title>
2953
2954 <indexterm>
2955 <primary>string slicing</primary>
2956 </indexterm>
2957
2958 <indexterm>
2959 <primary>substring</primary>
2960 </indexterm>
2961
2962 <indexterm>
2963 <primary>string</primary>
2964
2965 <secondary>slice</secondary>
2966 </indexterm>
2967
2968 <indexterm>
2969 <primary>string</primary>
2970
2971 <secondary>substring</secondary>
2972 </indexterm>
2973
2974 <para>You can slice a string in the same way as you <link
2975 linkend="dgui_template_exp_seqenceop_slice">slice a
2976 sequence</link> (see there), only here instead of sequence items
2977 you work with characters. Some differences are:</para>
2978
2979 <itemizedlist>
2980 <listitem>
2981 <para>Decreasing ranges aren't allowed for string slicing.
2982 (That's because unlike sequences, you seldom if ever want to
2983 show a string reversed, so if that happens, that's almost
2984 always the result of an oversight.)</para>
2985 </listitem>
2986
2987 <listitem>
2988 <para>If a value is both a string and a sequence (a
2989 multi-typed value), then slicing will slice the sequence
2990 instead of the string. When you are processing XML, such
2991 values are common. In such cases you can use
2992 <literal><replaceable>someXMLnode</replaceable>?string[<replaceable>range</replaceable>]</literal>
2993 to fore string slicing.</para>
2994 </listitem>
2995
2996 <listitem>
2997 <para>There's a legacy bug where a range with
2998 <emphasis>inclusive</emphasis> end that's one less than the
2999 starting index and is non-negative (like in
3000 <literal>"abc"[1..0]</literal>) will give an empty string
3001 instead of an error. (It should be an error as it's a
3002 decreasing range.) Currently this bug is emulated for backward
3003 compatibility, but you shouldn't utilize it, as in the future
3004 it will be certainly an error.</para>
3005 </listitem>
3006 </itemizedlist>
3007
3008 <para>Example:</para>
3009
3010 <programlisting role="template">&lt;#assign s = "ABCDEF"&gt;
3011 ${s[2..3]}
3012 ${s[2..&lt;4]}
3013 ${s[2..*3]}
3014 ${s[2..*100]}
3015 ${s[2..]}</programlisting>
3016
3017 <para>will print:</para>
3018
3019 <programlisting role="output">CD
3020 CD
3021 CDE
3022 CDEF
3023 CDEF</programlisting>
3024
3025 <note>
3026 <para>Some of the typical use-cases of string slicing is covered
3027 by convenient built-ins: <link
3028 linkend="ref_builtin_remove_beginning"><literal>remove_beginning</literal></link>,
3029 <link
3030 linkend="ref_builtin_remove_ending"><literal>remove_ending</literal></link>,
3031 <link
3032 linkend="ref_builtin_keep_before"><literal>keep_before</literal></link>,
3033 <link
3034 linkend="ref_builtin_keep_after"><literal>keep_after</literal></link>,
3035 <link
3036 linkend="ref_builtin_keep_before_last"><literal>keep_before_last</literal></link>,
3037 <link
3038 linkend="ref_builtin_keep_after_last"><literal>keep_after_last</literal></link></para>
3039 </note>
3040 </section>
3041 </section>
3042
3043 <section xml:id="dgui_template_exp_sequenceop">
3044 <title>Sequence operations</title>
3045
3046 <indexterm>
3047 <primary>sequence</primary>
3048
3049 <secondary>operations</secondary>
3050 </indexterm>
3051
3052 <section xml:id="dgui_template_exp_sequenceop_cat">
3053 <title>Concatenation</title>
3054
3055 <indexterm>
3056 <primary>concatenate sequences</primary>
3057 </indexterm>
3058
3059 <indexterm>
3060 <primary>joining sequences</primary>
3061 </indexterm>
3062
3063 <indexterm>
3064 <primary>sequence</primary>
3065
3066 <secondary>concatenate</secondary>
3067 </indexterm>
3068
3069 <indexterm>
3070 <primary>adding sequences</primary>
3071 </indexterm>
3072
3073 <para>You can concatenate sequences in the same way as strings,
3074 with <literal>+</literal>. Example:</para>
3075
3076 <programlisting role="template">&lt;#list ["Joe", "Fred"] + ["Julia", "Kate"] as user&gt;
3077 - ${user}
3078 &lt;/#list&gt;</programlisting>
3079
3080 <para>will print:</para>
3081
3082 <programlisting role="output">- Joe
3083 - Fred
3084 - Julia
3085 - Kate
3086 </programlisting>
3087
3088 <para>Note that sequence concatenation is not to be used for many
3089 repeated concatenations, like for appending items to a sequence
3090 inside a loop. It's just for things like <literal>&lt;#list users
3091 + admins as person&gt;</literal>. Although concatenating sequences
3092 is fast and is constant time (it's speed is independently of the
3093 size of the concatenated sequences), the resulting sequence will
3094 be always a little bit slower to read than the original two
3095 sequences were. Thus, after tens or hundreds of repeated
3096 concatenations the result can be impractically slow to
3097 reader.</para>
3098 </section>
3099
3100 <section xml:id="dgui_template_exp_seqenceop_slice">
3101 <title>Sequence slicing</title>
3102
3103 <indexterm>
3104 <primary>sequence slice</primary>
3105 </indexterm>
3106
3107 <indexterm>
3108 <primary>sequence</primary>
3109
3110 <secondary>slice</secondary>
3111 </indexterm>
3112
3113 <indexterm>
3114 <primary>subsequence</primary>
3115 </indexterm>
3116
3117 <para>With
3118 <literal><replaceable>seq</replaceable>[<replaceable>range</replaceable>]</literal>,
3119 were <literal><replaceable>range</replaceable></literal> is a
3120 range value <link linkend="dgui_template_exp_direct_ranges">as
3121 described here</link>, you can take a slice of the sequence. The
3122 resulting sequence will contain the items from the original
3123 sequence (<literal><replaceable>seq</replaceable></literal>) whose
3124 indexes are in the range. For example:</para>
3125
3126 <programlisting role="template">&lt;#assign seq = ["A", "B", "C", "D", "E"]&gt;
3127 &lt;#list seq[1..3] as i&gt;${i}&lt;/#list&gt;</programlisting>
3128
3129 <para>will print</para>
3130
3131 <programlisting role="output">BCD </programlisting>
3132
3133 <para>Furthermore, the items in the slice will be in the same
3134 order as in the range. Thus for example the above example with the
3135 <literal>3..1</literal> range would print
3136 <literal>DCB</literal>.</para>
3137
3138 <para>The numbers in the range must be valid indexes in the
3139 sequence, or else the processing of the template will be aborted
3140 with error. Like in the last example,
3141 <literal>seq[-1..0]</literal> would be an error as
3142 <literal>seq[-1]</literal> is invalid, also
3143 <literal>seq[1..5]</literal> would be because
3144 <literal>seq[5]</literal> is invalid. (Note that
3145 <literal>seq[100..&lt;100]</literal> or
3146 <literal>seq[100..*0]</literal> would be valid despite that 100 is
3147 out of bounds, because those ranges are empty.)</para>
3148
3149 <para>Length limited ranges
3150 (<literal><replaceable>start</replaceable>..*<replaceable>length</replaceable></literal>)
3151 and right-unbounded ranges
3152 (<literal><replaceable>start</replaceable>..</literal>) adapt to
3153 the length of the sliced sequence. They will slice out at most as
3154 many items as there is available:</para>
3155
3156 <programlisting role="template">&lt;#assign seq = ["A", "B", "C"]&gt;
3157
3158 Slicing with length limited ranges:
3159 - &lt;#list seq[0..*2] as i&gt;${i}&lt;/#list&gt;
3160 - &lt;#list seq[1..*2] as i&gt;${i}&lt;/#list&gt;
3161 - &lt;#list seq[2..*2] as i&gt;${i}&lt;/#list&gt; &lt;#-- Not an error --&gt;
3162 - &lt;#list seq[3..*2] as i&gt;${i}&lt;/#list&gt; &lt;#-- Not an error --&gt;
3163
3164 Slicing with right-unlimited ranges:
3165 - &lt;#list seq[0..] as i&gt;${i}&lt;/#list&gt;
3166 - &lt;#list seq[1..] as i&gt;${i}&lt;/#list&gt;
3167 - &lt;#list seq[2..] as i&gt;${i}&lt;/#list&gt;
3168 - &lt;#list seq[3..] as i&gt;${i}&lt;/#list&gt;</programlisting>
3169
3170 <para>This will print:</para>
3171
3172 <programlisting role="output">Slicing with length limited ranges:
3173 - AB
3174 - BC
3175 - C
3176 -
3177
3178 Slicing with right-unlimited ranges:
3179 - ABC
3180 - BC
3181 - C
3182 -</programlisting>
3183
3184 <para>Note above that slicing with length limited and right
3185 unbounded ranges allow the starting index to be past the last item
3186 <emphasis>by one</emphasis> (but no more).</para>
3187
3188 <note>
3189 <para>To split a sequence to slices of a given size, you should
3190 use the <link
3191 linkend="ref_builtin_chunk"><literal>chunk</literal></link>
3192 built-in.</para>
3193 </note>
3194 </section>
3195 </section>
3196
3197 <section xml:id="dgui_template_exp_hashop">
3198 <title>Hash operations</title>
3199
3200 <indexterm>
3201 <primary>hash</primary>
3202
3203 <secondary>operations</secondary>
3204 </indexterm>
3205
3206 <section xml:id="dgui_template_exp_hashop_cat">
3207 <title>Concatenation</title>
3208
3209 <indexterm>
3210 <primary>concatenate hashes</primary>
3211 </indexterm>
3212
3213 <indexterm>
3214 <primary>joining hashes</primary>
3215 </indexterm>
3216
3217 <indexterm>
3218 <primary>hash</primary>
3219
3220 <secondary>concatenate</secondary>
3221 </indexterm>
3222
3223 <indexterm>
3224 <primary>adding hashes</primary>
3225 </indexterm>
3226
3227 <para>You can concatenate hashes in the same way as strings, with
3228 <literal>+</literal>. If both hashes contain the same key, the
3229 hash on the right-hand side of the <literal>+</literal> takes
3230 precedence. Example:</para>
3231
3232 <programlisting role="template">&lt;#assign ages = {"Joe":23, "Fred":25} + {"Joe":30, "Julia":18}&gt;
3233 - Joe is ${ages.Joe}
3234 - Fred is ${ages.Fred}
3235 - Julia is ${ages.Julia}
3236 </programlisting>
3237
3238 <para>will print:</para>
3239
3240 <programlisting role="output">- Joe is 30
3241 - Fred is 25
3242 - Julia is 18</programlisting>
3243
3244 <para>Note that hash concatenation is not to be used for many
3245 repeated concatenations, like for adding items to a hash inside a
3246 loop. While adding together hashes is fast and is constant time
3247 (independent of the size of the hashes added), the resulting hash
3248 is a bit slower to read than the hashes added together. Thus after
3249 tens or hundreds of additions the result can be impractically slow
3250 to read.</para>
3251 </section>
3252 </section>
3253
3254 <section xml:id="dgui_template_exp_arit">
3255 <title>Arithmetical calculations</title>
3256
3257 <indexterm>
3258 <primary>arithmetic</primary>
3259 </indexterm>
3260
3261 <indexterm>
3262 <primary>math</primary>
3263 </indexterm>
3264
3265 <indexterm>
3266 <primary>addition</primary>
3267 </indexterm>
3268
3269 <indexterm>
3270 <primary>subtraction</primary>
3271 </indexterm>
3272
3273 <indexterm>
3274 <primary>division</primary>
3275 </indexterm>
3276
3277 <indexterm>
3278 <primary>modulus</primary>
3279 </indexterm>
3280
3281 <para>This is the basic 4-function calculator arithmetic plus the
3282 modulus operator. So the operators are:</para>
3283
3284 <itemizedlist spacing="compact">
3285 <listitem>
3286 <para>Addition: <literal>+</literal></para>
3287 </listitem>
3288
3289 <listitem>
3290 <para>Subtraction: <literal>-</literal></para>
3291 </listitem>
3292
3293 <listitem>
3294 <para>Multiplication: <literal>*</literal></para>
3295 </listitem>
3296
3297 <listitem>
3298 <para>Division: <literal>/</literal></para>
3299 </listitem>
3300
3301 <listitem>
3302 <para>Modulus (remainder) of integer operands:
3303 <literal>%</literal></para>
3304 </listitem>
3305 </itemizedlist>
3306
3307 <para>Example:</para>
3308
3309 <programlisting role="template">${100 - x * x}
3310 ${x / 2}
3311 ${12 % 10}</programlisting>
3312
3313 <para>Assuming that <literal>x</literal> is 5, it will print:</para>
3314
3315 <programlisting role="output">75
3316 2.5
3317 2</programlisting>
3318
3319 <para>Both operands must be expressions which evaluate to a
3320 numerical value. So the example below will cause an error when
3321 FreeMarker tries to evaluate it, since <literal>"5"</literal> is a
3322 string and not the number 5:</para>
3323
3324 <programlisting role="template">${3 * "5"} &lt;#-- WRONG! --&gt;</programlisting>
3325
3326 <para>There is an exception to the above rule. The
3327 <literal>+</literal> operator, is used to <link
3328 linkend="dgui_template_exp_stringop_interpolation">concatenate
3329 strings</link> as well. If on one side of <literal>+</literal> is a
3330 string and on the other side of <literal>+</literal> is a numerical
3331 value, then it will convert the numerical value to string (using the
3332 format appropriate for language of the page) and then use the
3333 <literal>+</literal> as string concatenation operator.
3334 Example:</para>
3335
3336 <programlisting role="template">${3 + "5"}</programlisting>
3337
3338 <programlisting role="output">35</programlisting>
3339
3340 <para>Generally, FreeMarker never converts a string to a number
3341 automatically, but it may convert a number to a string
3342 automatically.</para>
3343
3344 <para><indexterm>
3345 <primary>integer division</primary>
3346 </indexterm><indexterm>
3347 <primary>integer part</primary>
3348 </indexterm> People often want only the integer part of the result
3349 of a division (or of other calculations). This is possible with the
3350 <literal>int</literal> built-in. (Built-ins are explained <link
3351 linkend="dgui_template_exp_builtin">later</link>):</para>
3352
3353 <programlisting role="template">${(x/2)?int}
3354 ${1.1?int}
3355 ${1.999?int}
3356 ${-1.1?int}
3357 ${-1.999?int}</programlisting>
3358
3359 <para>Assuming that <literal>x</literal> is 5, it will print:</para>
3360
3361 <programlisting role="output">2
3362 1
3363 1
3364 -1
3365 -1</programlisting>
3366
3367 <para>Due to historical reasons, the <literal>%</literal> operator
3368 works by first truncating the operands to an integer number, and
3369 then returning the remainder of the division:</para>
3370
3371 <programlisting role="template">${12 % 5} &lt;#-- Prints 2 --&gt;
3372 ${12.9 % 5} &lt;#-- Prints 2 --&gt;
3373 ${12.1 % 5} &lt;#-- Prints 2 --&gt;
3374
3375 ${12 % 6} &lt;#-- Prints 0 --&gt;
3376 ${12 % 6.9} &lt;#-- Prints 0 --&gt;</programlisting>
3377
3378 <para>The sign of the result of <literal>%</literal> is the same as
3379 the sign of the left hand operand, and its absolute value is the
3380 same as if both operands where positive:</para>
3381
3382 <programlisting role="template">${-12 % -5} &lt;#-- Prints -2 --&gt;
3383 ${-12 % 5} &lt;#-- Prints -2 --&gt;
3384 ${12 % -5} &lt;#-- Prints 2 --&gt;
3385 </programlisting>
3386
3387 <para role="forProgrammers">About the precision of the operations:
3388 By default FreeMarker uses <literal>BigDecimal</literal>-s for all
3389 arithmetical calculations, to avoid rounding and overflow/underflow
3390 artifacts, and also keeps the result as
3391 <literal>BigDecimal</literal>-s. So <literal>+</literal> (addition),
3392 <literal>-</literal> (subtraction) and <literal>*</literal>
3393 (multiplication) are <quote>lossless</quote>. Again by default,
3394 <literal>/</literal> (division) results are calculated to 12
3395 decimals with half-up rounding (unless some operands have even more
3396 decimals, in which case it's calculated with that much decimals).
3397 All this behavior depends on the
3398 <literal>arithmetic_engine</literal> configuration setting
3399 (<literal>Configurable.setArithmericEngine(ArithmericEngine)</literal>)
3400 though, and some application might use a different value than the
3401 default, although that's highly uncommon.</para>
3402 </section>
3403
3404 <section xml:id="dgui_template_exp_comparison">
3405 <title>Comparison</title>
3406
3407 <indexterm>
3408 <primary>comparison operators</primary>
3409 </indexterm>
3410
3411 <para>Sometimes you want to know if two values are equal or not, or
3412 which value is the greater.</para>
3413
3414 <para>To show concrete examples I will use the <literal>if</literal>
3415 directive here. The usage of <literal>if</literal> directive is:
3416 <literal>&lt;#if
3417 <replaceable>expression</replaceable>&gt;...&lt;/#if&gt;</literal>,
3418 where expression must evaluate to a boolean value or else an error
3419 will abort the processing of the template. If the value of
3420 expression is <literal>true</literal> then the things between the
3421 begin and end-tag will be processed, otherwise they will be
3422 skipped.</para>
3423
3424 <para>To test two values for equality you use <literal>==</literal>
3425 (or <literal>=</literal> as a <emphasis>deprecated</emphasis>
3426 alternative) To test two values for inequality you use
3427 <literal>!=</literal>. For example, assume that
3428 <literal>user</literal> is <quote>Big Joe</quote>:</para>
3429
3430 <programlisting role="template">&lt;#if <emphasis>user == "Big Joe"</emphasis>&gt;
3431 It is Big Joe
3432 &lt;/#if&gt;
3433 &lt;#if <emphasis>user != "Big Joe"</emphasis>&gt;
3434 It is not Big Joe
3435 &lt;/#if&gt;</programlisting>
3436
3437 <para>The <literal>user == "Big Joe"</literal> expression in the
3438 <literal>&lt;#if ...&gt;</literal> will evaluate to the boolean
3439 <literal>true</literal>, so the above will say <quote>It is Big
3440 Joe</quote>.</para>
3441
3442 <para>The expressions on both sides of the <literal>==</literal> or
3443 <literal>!=</literal> must evaluate to a scalar (not a sequence or
3444 hash). Furthermore, the two scalars must have the same type (i.e.
3445 strings can only be compared to strings and numbers can only be
3446 compared to numbers, etc.) or else an error will abort template
3447 processing. For example <literal>&lt;#if 1 == "1"&gt;</literal> will
3448 cause an error. Note that FreeMarker does exact comparison, so
3449 string comparisons are case and white-space sensitive:
3450 <literal>"x"</literal> and <literal>""</literal> and
3451 <literal>"X"</literal> are not equal values.</para>
3452
3453 <para>For numerical and date, time and date-time values you can also
3454 use <literal>&lt;</literal>, <literal>&lt;=</literal>,
3455 <literal>&gt;=</literal> and <literal>&gt;</literal>. You can't use
3456 them for strings! Example:</para>
3457
3458 <programlisting role="template">&lt;#if x <emphasis>&lt;=</emphasis> 12&gt;
3459 x is less or equivalent with 12
3460 &lt;/#if&gt;</programlisting>
3461
3462 <para>There's a problem with <literal>&gt;=</literal> and
3463 <literal>&gt;</literal>. FreeMarker interprets the
3464 <literal>&gt;</literal> character as the closing character of the
3465 FTL tag. To prevent this, you can use <literal>lt</literal> instead
3466 of <literal>&lt;</literal>, <literal>lte</literal> instead of
3467 <literal>&lt;=</literal>, <literal>gt</literal> instead of
3468 <literal>&gt;</literal> and <literal>gte</literal> instead of
3469 <literal>&gt;=</literal>, like in <literal>&lt;#if x gt
3470 y&gt;</literal>. Another trick it to put the expression into <link
3471 linkend="dgui_template_exp_parentheses">parentheses</link> like in
3472 <literal>&lt;#if (x &gt; y)&gt;</literal>, although it's considered
3473 to be less elegant.</para>
3474
3475 <para>FreeMarker supports some more syntactical alternatives:</para>
3476
3477 <itemizedlist>
3478 <listitem>
3479 <para><literal>&amp;gt;</literal> and
3480 <literal>&amp;lt;</literal> can also be used, like in:
3481 <literal>&lt;#if x &amp;gt; y&gt;</literal> or <literal>&lt;#if
3482 x &amp;gt;= y&gt;</literal>. This isn't meant to be entered
3483 manually; it's to work around cases where the template gets
3484 XML/HTML escaped and the user can't easily prevent that
3485 happening. Note that in general FTL does not support entity
3486 references (the
3487 <literal>&amp;<replaceable>...</replaceable>;</literal> things)
3488 in FTL tags; it's just an exception with these operators.</para>
3489 </listitem>
3490
3491 <listitem>
3492 <para>Deprecated forms: <literal>\lt</literal>,
3493 <literal>\lte</literal>, <literal>\gt</literal> and
3494 <literal>\gte</literal>. These are the same as the ones without
3495 the backslash.</para>
3496 </listitem>
3497 </itemizedlist>
3498 </section>
3499
3500 <section xml:id="dgui_template_exp_logicalop">
3501 <title>Logical operations</title>
3502
3503 <indexterm>
3504 <primary>boolean</primary>
3505
3506 <secondary>operations</secondary>
3507 </indexterm>
3508
3509 <indexterm>
3510 <primary>logical operations</primary>
3511 </indexterm>
3512
3513 <indexterm>
3514 <primary>or</primary>
3515 </indexterm>
3516
3517 <indexterm>
3518 <primary>and</primary>
3519 </indexterm>
3520
3521 <indexterm>
3522 <primary>not</primary>
3523 </indexterm>
3524
3525 <para>Just the usual logical operators:</para>
3526
3527 <itemizedlist spacing="compact">
3528 <listitem>
3529 <para>Logical or: <literal>||</literal></para>
3530 </listitem>
3531
3532 <listitem>
3533 <para>Logical and: <literal>&amp;&amp;</literal></para>
3534 </listitem>
3535
3536 <listitem>
3537 <para>Logical not: <literal>!</literal></para>
3538 </listitem>
3539 </itemizedlist>
3540
3541 <para>The operators will work with boolean values only. Otherwise an
3542 error will abort the template processing.</para>
3543
3544 <para>Example:</para>
3545
3546 <programlisting role="template">&lt;#if x &lt; 12 <emphasis>&amp;&amp;</emphasis> color == "green"&gt;
3547 We have less than 12 things, and they are green.
3548 &lt;/#if&gt;
3549 &lt;#if <emphasis>!</emphasis>hot&gt; &lt;#-- here hot must be a boolean --&gt;
3550 It's not hot.
3551 &lt;/#if&gt;</programlisting>
3552
3553 <para>FreeMarker supports some more syntactical alternatives:</para>
3554
3555 <itemizedlist>
3556 <listitem>
3557 <para><literal>\and</literal> (since FreeMarker 2.3.27): In some
3558 applications using <literal>&amp;&amp;</literal> causes problems
3559 as it's not valid in XML or HTML. While FreeMarker templates was
3560 never intended to be valid XML/HTML, only their output should be
3561 that, in reality there are some applications that expect the
3562 template itself to be valid XML/HTML regardless. This syntax is
3563 a workaround for such cases. Also note that unlike with the
3564 comparison operators, <literal>and</literal> without
3565 <literal>\</literal> is not supported due to backward
3566 compatibility restrictions.</para>
3567 </listitem>
3568
3569 <listitem>
3570 <para><literal>&amp;amp;&amp;amp;</literal> (since FreeMarker
3571 2.3.27): This isn't meant to be entered manually; it's to work
3572 around cases where the template gets XML/HTML escaped and the
3573 user can't easily prevent that happening. Note that in general
3574 FTL does not support entity references (the
3575 <literal>&amp;<replaceable>...</replaceable>;</literal> things)
3576 in FTL tags; it's just an exception with these operators.</para>
3577 </listitem>
3578
3579 <listitem>
3580 <para>Deprecated forms: <literal>&amp;</literal> and
3581 <literal>|</literal>. Don't use them anymore.</para>
3582 </listitem>
3583 </itemizedlist>
3584 </section>
3585
3586 <section xml:id="dgui_template_exp_builtin">
3587 <title>Built-ins</title>
3588
3589 <indexterm>
3590 <primary>built-in</primary>
3591 </indexterm>
3592
3593 <para>Built-ins are like methods that are added to the objects by
3594 FreeMarker. To prevent name clashes with actual methods and other
3595 sub-variables, instead of dot (<literal>.</literal>), you separate
3596 them from the parent object with question mark
3597 (<literal>?</literal>). For example, if you want to ensure that
3598 <literal>path</literal> has an initial <literal>/</literal> then you
3599 could write <literal>path?ensure_starts_with('/')</literal>. The
3600 Java object behind <literal>path</literal> (a
3601 <literal>String</literal> most certainly) doesn't have such method,
3602 FreeMarker adds it. For brevity, if the method has no parameters,
3603 you <emphasis>must</emphasis> omit the <literal>()</literal>, like,
3604 to get the length of <literal>path</literal>, you have to write
3605 <literal>path?length</literal>, <emphasis>not</emphasis>
3606 <literal>path?length()</literal>.</para>
3607
3608 <para>The other reason why built-ins are crucial is that normally
3609 (though it depends on configuration settings), FreeMarker doesn't
3610 expose the Java API of the objects. So despite that Java's
3611 <literal>String</literal> has a <literal>length()</literal> method,
3612 it's hidden from the template, you <emphasis>have to</emphasis> use
3613 <literal>path?length</literal> instead. The advantage of that is
3614 that thus the template doesn't depend on the exactly type of the
3615 underlying Java objects. (Like <literal>path</literal> is maybe a
3616 <literal>java.nio.Path</literal> behind the scenes, but if the
3617 programmers has configure FreeMarker to expose
3618 <literal>Path</literal> objects as FTL strings, the template won't
3619 be aware of that, and <literal>?length</literal> will work, despite
3620 that <literal>java.nio.Path</literal> has no similar method.)</para>
3621
3622 <para>You can find some of the <link
3623 linkend="topic.commonlyUsedBuiltIns">most commonly used built-ins
3624 mentioned here</link>, and the <link linkend="ref_builtins">complete
3625 list of built-ins in the Reference</link>. For now, just a few of
3626 the more important ones:</para>
3627
3628 <para>Example:</para>
3629
3630 <programlisting role="template">${testString?upper_case}
3631 ${testString?html}
3632 ${testString?upper_case?html}
3633
3634 ${testSequence?size}
3635 ${testSequence?join(", ")}</programlisting>
3636
3637 <para>Assuming that <literal>testString</literal> stores the string
3638 <quote>Tom &amp; Jerry</quote>, and testSequnce stores the strings
3639 <quote>foo</quote>, <quote>bar</quote> and <quote>baz</quote>, the
3640 output will be:</para>
3641
3642 <programlisting role="output">TOM &amp; JERRY
3643 Tom &amp;amp; Jerry
3644 TOM &amp;amp; JERRY
3645
3646 3
3647 foo, bar, baz</programlisting>
3648
3649 <para>Note the <literal>test?upper_case?html</literal> above. Since
3650 the result of <literal>test?upper_case</literal> is a string, you
3651 can apply the <literal>html</literal> built-in on it.</para>
3652
3653 <para>Naturally, the left side of the built-in can be arbitrary
3654 expression, not just a variable name:</para>
3655
3656 <programlisting role="template">${testSeqence[1]?cap_first}
3657 ${"horse"?cap_first}
3658 ${(testString + " &amp; Duck")?html}</programlisting>
3659
3660 <programlisting role="output">Bar
3661 Horse
3662 Tom &amp;amp; Jerry &amp;amp; Duck</programlisting>
3663 </section>
3664
3665 <section xml:id="dgui_template_exp_methodcall">
3666 <title>Method call</title>
3667
3668 <indexterm>
3669 <primary>call a method</primary>
3670 </indexterm>
3671
3672 <indexterm>
3673 <primary>method</primary>
3674
3675 <secondary>call</secondary>
3676 </indexterm>
3677
3678 <para>If you have a method then you can use the method call
3679 operation on it. The method call operation is a comma-separated list
3680 of expressions in parentheses. These values are called parameters.
3681 The method call operation passes these values to the method which
3682 will in turn return a result. This result will be the value of the
3683 whole method call expression.</para>
3684
3685 <para>For example, assume the programmers have made available a
3686 method variable called <literal>repeat</literal>. You give a string
3687 as the first parameter, and a number as the second parameter, and it
3688 returns a string which repeats the first parameter the number of
3689 times specified by the second parameter.</para>
3690
3691 <programlisting role="template">${repeat("Foo", 3)}</programlisting>
3692
3693 <para>will print:</para>
3694
3695 <programlisting role="output">FooFooFoo</programlisting>
3696
3697 <para>Here <literal>repeat</literal> was evaluated to the method
3698 variable (according to how you <link
3699 linkend="dgui_template_exp_var_toplevel">access top-level
3700 variables</link>) and then <literal>("What", 3)</literal> invoked
3701 that method.</para>
3702
3703 <para>I would like to emphasize that method calls are just plain
3704 expressions, like everything else. So this:</para>
3705
3706 <programlisting role="template">${repeat(repeat("x", 2), 3) + repeat("Foo", 4)?upper_case}</programlisting>
3707
3708 <para>will print this:</para>
3709
3710 <programlisting role="output">xxxxxxFOOFOOFOOFOO</programlisting>
3711 </section>
3712
3713 <section xml:id="dgui_template_exp_missing">
3714 <title>Handling missing values</title>
3715
3716 <note>
3717 <para>These operators exist since FreeMarker 2.3.7 (replacing the
3718 <literal>default</literal>, <literal>exists</literal> and
3719 <literal>if_exists</literal> built-ins).</para>
3720 </note>
3721
3722 <indexterm>
3723 <primary>undefined variable</primary>
3724 </indexterm>
3725
3726 <indexterm>
3727 <primary>missing variable</primary>
3728 </indexterm>
3729
3730 <indexterm>
3731 <primary>null</primary>
3732 </indexterm>
3733
3734 <indexterm>
3735 <primary>handling null-s</primary>
3736 </indexterm>
3737
3738 <indexterm>
3739 <primary>error handling</primary>
3740 </indexterm>
3741
3742 <para>As we explained earlier, an error will occur and abort the
3743 template processing if you try to access a missing variable. However
3744 two special operators can suppress this error, and handle the
3745 problematic situation. The handled variable can be top-level
3746 variable, hash subvariable, or sequence subvariable as well.
3747 Furthermore these operators handle the situation when a method call
3748 doesn't return a value <phrase role="forProgrammers">(from the
3749 viewpoint of Java programmers: it returns <literal>null</literal> or
3750 it's return type is <literal>void</literal>)</phrase>, so it's more
3751 correct to say that these operators handle missing values in
3752 general, rather than just missing variables.</para>
3753
3754 <para><phrase role="forProgrammers">For those who know what's Java
3755 <literal>null</literal>, FreeMarker 2.3.<replaceable>x</replaceable>
3756 treats them as missing values. Simply, the template language doesn't
3757 know the concept of <literal>null</literal>. For example, if you
3758 have a bean that has a <literal>maidenName</literal> property, and
3759 the value of that property is <literal>null</literal>, then that's
3760 the same as if there were no such property at all, as far as the
3761 template is concerned (assuming you didn't configured FreeMarker to
3762 use some extreme object wrapper, that is). The result of a method
3763 call that returns <literal>null</literal> is also treated as a
3764 missing variable (again, assuming that you use some usual object
3765 wrapper). See more <link linkend="faq_null">in the
3766 FAQ</link>.</phrase></para>
3767
3768 <note>
3769 <para>If you wonder why is FreeMarker so picky about missing
3770 variables, <link linkend="faq_picky_about_missing_vars">read this
3771 FAQ entry</link>.</para>
3772 </note>
3773
3774 <section xml:id="dgui_template_exp_missing_default">
3775 <title>Default value operator</title>
3776
3777 <indexterm>
3778 <primary>default value operator</primary>
3779 </indexterm>
3780
3781 <para>Synopsis:
3782 <literal><replaceable>unsafe_expr</replaceable>!<replaceable>default_expr</replaceable></literal>
3783 or <literal><replaceable>unsafe_expr</replaceable>!</literal> or
3784 <literal>(<replaceable>unsafe_expr</replaceable>)!<replaceable>default_expr</replaceable></literal>
3785 or
3786 <literal>(<replaceable>unsafe_expr</replaceable>)!</literal></para>
3787
3788 <para>This operator allows you to specify a default value for the
3789 case when the value is missing.</para>
3790
3791 <para>Example. Assume no variable called <literal>mouse</literal>
3792 is present:</para>
3793
3794 <programlisting role="template">${mouse!"No mouse."}
3795 &lt;#assign mouse="Jerry"&gt;
3796 ${mouse!"No mouse."}</programlisting>
3797
3798 <para>The output will be:</para>
3799
3800 <programlisting role="output">No mouse.
3801 Jerry</programlisting>
3802
3803 <para>The default value can be any kind of expression, so it
3804 doesn't have to be a string. For example you can write
3805 <literal>hits!0</literal> or <literal>colors!["red", "green",
3806 "blue"]</literal>. There is no restriction regarding the
3807 complexity of the expression that specifies the default value, for
3808 example you can write: <literal>cargo.weight!(item.weight *
3809 itemCount + 10)</literal>.</para>
3810
3811 <warning>
3812 <para>If you have a composite expression after the
3813 <literal>!</literal>, like <literal>1 + x</literal>,
3814 <emphasis>always</emphasis> use parenthesses, like
3815 <literal>${x!(1 + y)}</literal> or <literal>${(x!1) +
3816 y)}</literal>, depending on which interpretation you meant.
3817 That's needed because due to a programming mistake in FreeMarker
3818 2.3.x, the precedence of <literal>!</literal> (when it's used as
3819 default value operator) is very low at its right side. This
3820 means that, for example, <literal>${x!1 + y}</literal> is
3821 misinterpreted by FreeMarker as <literal>${x!(1 + y)}</literal>
3822 while it should mean <literal>${(x!1) + y}</literal>. This
3823 programming error will be fixed in FreeMarker 2.4, so you should
3824 not utilize this wrong behavior, or else your templates will
3825 break with FreeMarker 2.4!</para>
3826 </warning>
3827
3828 <para>If the default value is omitted, then it will be empty
3829 string and empty sequence and empty hash at the same time. (This
3830 is possible because FreeMarker allows multi-type values.) Note the
3831 consequence that you can't omit the default value if you want it
3832 to be <literal>0</literal> or <literal>false</literal>.
3833 Example:</para>
3834
3835 <programlisting role="template">(${mouse!})
3836 &lt;#assign mouse = "Jerry"&gt;
3837 (${mouse!})</programlisting>
3838
3839 <para>The output will be:</para>
3840
3841 <programlisting role="output">()
3842 (Jerry)</programlisting>
3843
3844 <warning>
3845 <para>Due to syntactical ambiguities <literal>&lt;@something
3846 a=x! b=y /&gt;</literal> will be interpreted as
3847 <literal>&lt;@something a=x!(b=y) /&gt;</literal>, that is, the
3848 <literal>b=y</literal> will be interpreted as a comparison that
3849 gives the default value for <literal>x</literal>, rather than
3850 the specification of the <literal>b</literal> parameter. To
3851 prevent this, write: <literal>&lt;@something a=(x!) b=y
3852 /&gt;</literal></para>
3853 </warning>
3854
3855 <para>You can use this operator in two ways with non-top-level
3856 variables:</para>
3857
3858 <programlisting role="template">product.color!"red"</programlisting>
3859
3860 <para>This will handle if <literal>color</literal> is missing
3861 inside <literal>product</literal> (and returns
3862 <literal>"red"</literal> if so), but will not handle if
3863 <literal>product</literal> is missing. That is, the
3864 <literal>product</literal> variable itself must exist, otherwise
3865 the template processing will die with error.</para>
3866
3867 <programlisting role="template">(product.color)!"red"</programlisting>
3868
3869 <para>This will handle if <literal>product.color</literal> is
3870 missing. That is, if <literal>product</literal> is missing, or
3871 <literal>product</literal> exists but it does not contain
3872 <literal>color</literal>, the result will be
3873 <literal>"red"</literal>, and no error will occur. The important
3874 difference between this and the previous example is that when
3875 surrounded with parentheses, it is allowed for any component of
3876 the expression to be undefined, while without parentheses only the
3877 last component of the expression is allowed to be
3878 undefined.</para>
3879
3880 <para>Of course, the default value operator can be used with
3881 sequence sub variables as well:</para>
3882
3883 <programlisting role="template">&lt;#assign seq = ['a', 'b']&gt;
3884 ${seq[0]!'-'}
3885 ${seq[1]!'-'}
3886 ${seq[2]!'-'}
3887 ${seq[3]!'-'}</programlisting>
3888
3889 <para>the outpur will be:</para>
3890
3891 <programlisting role="output">a
3892 b
3893 -
3894 -</programlisting>
3895
3896 <para>A negative sequence index (as
3897 <literal>seq[-1]!'-'</literal>) will always cause an error, you
3898 can't suppress that with this or any other operator.</para>
3899 </section>
3900
3901 <section xml:id="dgui_template_exp_missing_test">
3902 <title>Missing value test operator</title>
3903
3904 <indexterm>
3905 <primary>existence test operator</primary>
3906 </indexterm>
3907
3908 <indexterm>
3909 <primary>missing value test operator</primary>
3910 </indexterm>
3911
3912 <indexterm>
3913 <primary>testing for null</primary>
3914 </indexterm>
3915
3916 <indexterm>
3917 <primary>testing for missing</primary>
3918 </indexterm>
3919
3920 <indexterm>
3921 <primary>testing for undefined</primary>
3922 </indexterm>
3923
3924 <indexterm>
3925 <primary>is null</primary>
3926 </indexterm>
3927
3928 <para>Synopsis:
3929 <literal><replaceable>unsafe_expr</replaceable>??</literal> or
3930 <literal>(<replaceable>unsafe_expr</replaceable>)??</literal></para>
3931
3932 <para>This operator tells if a value is missing or not. Depending
3933 on that, the result is either <literal>true</literal> or
3934 <literal>false</literal>.</para>
3935
3936 <para>Example. Assume no variable called <literal>mouse</literal>
3937 is present:</para>
3938
3939 <programlisting role="template">&lt;#if mouse??&gt;
3940 Mouse found
3941 &lt;#else&gt;
3942 No mouse found
3943 &lt;/#if&gt;
3944 Creating mouse...
3945 &lt;#assign mouse = "Jerry"&gt;
3946 &lt;#if mouse??&gt;
3947 Mouse found
3948 &lt;#else&gt;
3949 No mouse found
3950 &lt;/#if&gt;</programlisting>
3951
3952 <para>The output will be:</para>
3953
3954 <programlisting role="output"> No mouse found
3955 Creating mouse...
3956 Mouse found</programlisting>
3957
3958 <para>With non-top-level variables the rules are the same as with
3959 the default value operator, that is, you can write
3960 <literal>product.color??</literal> and
3961 <literal>(product.color)??</literal>.</para>
3962 </section>
3963 </section>
3964
3965 <section xml:id="dgui_template_exp_assignment">
3966 <title>Assignment Operators</title>
3967
3968 <para>These are actually not expressions, but parts of the syntax of
3969 the assignment directives, such as <link
3970 linkend="ref_directive_assign"><literal>assign</literal></link>,
3971 <link linkend="ref_directive_local"><literal>local</literal></link>
3972 and <link
3973 linkend="ref_directive_global"><literal>global</literal></link>. As
3974 such, they can't be used anywhere else.</para>
3975
3976 <para><literal>&lt;#assign x += y&gt;</literal> is shorthand for
3977 <literal>&lt;#assign x = x + y&gt;</literal>, <literal>&lt;#assign x
3978 *= y&gt;</literal> is shorthand for <literal>&lt;#assign x = x *
3979 y&gt;</literal>, and so on.</para>
3980
3981 <para><literal>&lt;#assign x++&gt;</literal> differs from
3982 <literal>&lt;#assign x += 1&gt;</literal> (or <literal>&lt;#assign x
3983 = x + 1&gt;</literal>) in that it always does arithmetical addition
3984 (and fails if the variable is not a number), while the others are
3985 overloaded to do string and sequence concatenation and hash
3986 addition. <literal>&lt;#assign x--&gt;</literal> is shorthand for
3987 <literal>&lt;#assign x -= 1&gt;</literal>.</para>
3988 </section>
3989
3990 <section xml:id="dgui_template_exp_parentheses">
3991 <title>Parentheses</title>
3992
3993 <indexterm>
3994 <primary>parentheses</primary>
3995 </indexterm>
3996
3997 <para>Parentheses can be used to group any expressions. Some
3998 examples:</para>
3999
4000 <programlisting role="template"> &lt;#-- Output will be: --&gt;
4001 ${3 * 2 + 2} &lt;#-- 8 --&gt;
4002 ${3 * (2 + 2)} &lt;#-- 12 --&gt;
4003 ${3 * ((2 + 2) * (1 / 2))} &lt;#-- 6 --&gt;
4004 ${"green " + "mouse"?upper_case} &lt;#-- green MOUSE --&gt;
4005 ${("green " + "mouse")?upper_case} &lt;#-- GREEN MOUSE --&gt;
4006 &lt;#if !(color == "red" || color == "green")&gt;
4007 The color is nor red nor green
4008 &lt;/#if&gt;</programlisting>
4009
4010 <para>Note that the parentheses of a <link
4011 linkend="dgui_template_exp_methodcall">method call
4012 expressions</link> have nothing to do with the parentheses used for
4013 grouping.</para>
4014 </section>
4015
4016 <section xml:id="dgui_template_exp_whitespace">
4017 <title>White-space in expressions</title>
4018
4019 <para>FTL ignores superfluous <link
4020 linkend="gloss.whiteSpace">white-space</link> in expressions. So
4021 these are totally equivalent:</para>
4022
4023 <programlisting role="template">${x + ":" + book.title?upper_case}</programlisting>
4024
4025 <para>and</para>
4026
4027 <programlisting role="template">${x+":"+book.title?upper_case}</programlisting>
4028
4029 <para>and</para>
4030
4031 <programlisting role="template">${
4032 x
4033 + ":" + book . title
4034 ? upper_case
4035 }</programlisting>
4036 </section>
4037
4038 <section xml:id="dgui_template_exp_precedence">
4039 <title>Operator precedence</title>
4040
4041 <indexterm>
4042 <primary>precedence</primary>
4043 </indexterm>
4044
4045 <indexterm>
4046 <primary>operator precedence</primary>
4047 </indexterm>
4048
4049 <para>The following table shows the precedence assigned to the
4050 operators. The operators in this table are listed in precedence
4051 order: the higher in the table an operator appears, the higher its
4052 precedence. Operators with higher precedence are evaluated before
4053 operators with a relatively lower precedence. Operators on the same
4054 line have equal precedence. When binary operators (operators with
4055 two <quote>parameters</quote>, as <literal>+</literal> and
4056 <literal>-</literal>) of equal precedence appear next to each other,
4057 they are evaluated in left-to-right order.</para>
4058
4059 <informaltable border="1">
4060 <thead>
4061 <tr>
4062 <th>Operator group</th>
4063
4064 <th>Operators</th>
4065 </tr>
4066 </thead>
4067
4068 <tbody>
4069 <tr>
4070 <td>highest precedence operators</td>
4071
4072 <td><literal>[<replaceable>subvarName</replaceable>]
4073 [<replaceable>subStringRange</replaceable>] . ?
4074 (<replaceable>methodParams</replaceable>)
4075 <replaceable>expr</replaceable>!
4076 <replaceable>expr</replaceable>??</literal></td>
4077 </tr>
4078
4079 <tr>
4080 <td>unary prefix operators</td>
4081
4082 <td><literal>+<replaceable>expr</replaceable>
4083 -<replaceable>expr</replaceable> !expr</literal></td>
4084 </tr>
4085
4086 <tr>
4087 <td>multiplicative operators</td>
4088
4089 <td><literal>* / %</literal></td>
4090 </tr>
4091
4092 <tr>
4093 <td>additive operators</td>
4094
4095 <td><literal>+ -</literal></td>
4096 </tr>
4097
4098 <tr>
4099 <td>numerical ranges</td>
4100
4101 <td><literal>..</literal> <literal>..&lt;</literal>
4102 <literal>..!</literal> <literal>..*</literal></td>
4103 </tr>
4104
4105 <tr>
4106 <td>relational operators</td>
4107
4108 <td><literal>&lt; &gt; &lt;= &gt;=</literal> (and equivalents:
4109 <literal>gt</literal>, <literal>lt</literal>, etc.)</td>
4110 </tr>
4111
4112 <tr>
4113 <td>equality operators</td>
4114
4115 <td><literal>== !=</literal> (and equivalents:
4116 <literal>=</literal>)</td>
4117 </tr>
4118
4119 <tr>
4120 <td>logical <quote>and</quote> operator</td>
4121
4122 <td><literal>&amp;&amp;</literal></td>
4123 </tr>
4124
4125 <tr>
4126 <td>logical <quote>or</quote> operator</td>
4127
4128 <td><literal>||</literal></td>
4129 </tr>
4130 </tbody>
4131 </informaltable>
4132
4133 <para>For those of you who know C, Java language or JavaScript, note
4134 that the precedence rules are the same as in those languages, except
4135 that FTL has some operators that do not exist in those
4136 languages.</para>
4137
4138 <para>The default value operator
4139 (<literal><replaceable>exp</replaceable>!<replaceable>exp</replaceable></literal>)