Show last authors
1 {{box cssClass="floatinginfobox" title="**Contents**"}}
2 {{toc depth="2" start="2"/}}
3 {{/box}}
4
5 = How to use Velocity in XWiki pages =
6
7 by Guillaume Delhumeau
8 July 2013
9
10
11 == What is it? ==
12
13 === ===
14
15 * Velocity is a **template** language.
16 * It describes what your page should be.
17 ** Which means it **control** what you **display**.
18
19 Examples:
20
21 * display the name of the user
22 * display an image under certain circonstances only
23 * display a list of all the blog categories
24
25 === Example ===
26
27 {{code language="velocity"}}
28 {{velocity}}
29 Welcome $xcontext.user !
30 #if($hasAdmin)
31 You will see the following picture because you are an administrator:
32 image:picture.jpg
33 #end
34 {{/velocity}}
35 {{/code}}
36
37 Will output:
38 {{image reference="sample1.png"/}}
39
40 === ===
41
42 * With XWiki and Velocity, you can retrieve informations contained in other pages
43
44 {{code language="velocity"}}
45 #set($docRef = $services.model.createDocumentReference('', 'OtherSpace', 'OtherPage'))
46 #set($document = $xwiki.getDocument($docRef))
47 The content of the other document is:
48 $document.getContent()
49 {{/code}}
50
51
52 {{image reference="serrure.jpg"/}}
53
54 === ===
55
56 * or do advanced searches throught the wiki (via the //Query Module//) :
57 ** //« give me all the blog entries posted during the month of july 2012 and that are not archived and that have at least 3 comments and... »//
58
59 {{image reference="detective.jpg"/}}
60
61 === ===
62
63 * But XWiki also allows you to use Velocity to **save** things in the wiki.
64
65 {{code language="velocity"}}
66 #set($object = $doc.getObject('XWiki.XWikiUsers'))
67 $object.set('first_name', 'Nobody')
68 $doc.save()
69 {{/code}}
70
71
72 {{image reference="nobody.jpg"/}}
73
74 == Principles ==
75
76 === Lines ===
77
78 * A line begining by '#' is a Velocity instruction
79 * All other lines are normal lines
80
81 {{code language="velocity"}}
82 ## This is a velocity comment - a comment is never displayed and is used to
83 ## add useful information inside a source code.
84 #set($myVar = 42)
85 ## The line above was a velocity instruction
86 This line is a normal line
87 {{/code}}
88
89 === Variables ===
90
91 * A //variable// is like a box that can contains data: text, numbers, objects, etc...
92 * A variable is always prefixed by a dollar '$'.
93 * To create a variable, just use the //#set()// Velocity instruction
94
95 {{code language="velocity"}}
96 #set($myVar = 42)
97 {{/code}}
98
99 * If a variable is inside a normal line, the content of the variable will be displayed:
100
101 {{code language="velocity"}}
102 #set($myVar = 42)
103 I am $myVar years old.
104 {{/code}}
105
106 will display:
107
108 {{image reference="variables.png"/}}
109
110 === ===
111
112 Some variables are already created by XWiki when you write a Velocity code, and you can use them.
113
114
115 This is some of them:
116
117 * //$hasEdit// : this variable tells us if the current user has the edit rights on the current page
118 * //$isGuest// : this variable tells us if the current user is a guest
119 * //$doc// : this variable represents the current document.
120 * //$xwiki// : this special variable is a tool to perform complicated stuffs
121 * //$request// : gives a lot of informations about the current request (like the referer, the query string, etc...)
122
123 === Methods ===
124
125 * Some variable are //objects//. An object can contains //variables// and //methods//.
126 * A method is like an //action// that the object can perform.
127 * Some actions give you an information, some just perform something.
128 * To call them, you write //$someObject.someMethod()// - with the '()'.
129
130 Examples:
131
132 {{code language="velocity"}}
133 ## will save the current document:
134 $doc.save()
135 ## will give you the content of the document:
136 $doc.getContent()
137 ## this method takes a "parameter", a text, which will be the new title:
138 $doc.setTitle("My new title")
139 ## will give you the current skin
140 $xwiki.getSkin()
141 {{/code}}
142
143 === Class ===
144
145 * Every object is different, they don't have the same variables and methods.
146 * But every object is an //instance// of a //class//.
147 * A //class// is like a model that describes what the object will have.
148 ** For example, the //Document// class has a //save// method, so every objects that are //instances// of //Document// will have the //save// method.
149 ** The //String// class has a //length// variable, so every instances of //String// will have this variable too.
150
151 === ===
152
153 * You can use the following code to know what is the class of an object:
154
155 {{code language="velocity"}}
156 #set($myVar = 42)
157 $myVar.class.name ## will display 'java.lang.Integer'
158 #set($myVar2 = "This is a text")
159 $myVar2.class.name ## will display 'java.lang.String'
160 $doc.class.name ## will display 'com.xpn.xwiki.api.Document'
161 $xwiki.class.name ## will display 'com.xpn.xwiki.api.XWiki'
162 {{/code}}
163
164
165 {{image reference="class.jpg"/}}
166
167 === ===
168
169 * Now that you know the class of your object, you can google it to have its documentation!
170 * With this documentation, you will be able to knows what method you can use.
171 ** Example with //java.lang.String//
172
173 {{image reference="javadoc.png"/}}
174
175 === ===
176
177 * As you may have notice, the classes come from the //Java// world.
178 * The documentation about the java classes is called //Javadoc//.
179 * So you can use the the //Javadoc// for Velocity too!
180
181 {{image reference="java.jpg"/}}
182
183 == Basic instructions ==
184
185 === Conditions ===
186
187 * When you want to display something only under certain circounstances, you can use the //#if// command.
188
189 {{code language="velocity"}}
190 #if($isGuest)
191 Welcome visitor! You should subscribe to the wiki !
192 #end
193 {{/code}}
194
195 * You can also use the //#else// command:
196
197 {{code language="velocity"}}
198 #if($isGuest)
199 Welcome visitor! You should subscribe to the wiki !
200 #else
201 Hello $xcontext.user! I'm happy to see a registred user, I hate visitors!
202 #end
203 {{/code}}
204
205
206 {{image reference="visitors.jpg"/}}
207
208 === Conditions (bis) ===
209
210 * You can compare variables, with the following operators:
211 ** **//==//** : compare if the variables are equals
212 ** **//!=//** : say if the variables are differents
213 ** **//>//** : say if the variable is superior to the other
214 ** **//<//** : do the oposite
215 ** **//>=//** : say if the variable is superior or equal to the other
216 ** **//<=//** : say if the variable is inferior or equal to the other
217
218 * You can create complicated conditions, with the logic operators:
219 ** **//&&//** : which means **"AND"**.
220 ** **//||//** : which means **"OR"**.
221 ** **//!//** : which means **"NOT"**.
222
223 === Examples ===
224
225 {{code language="velocity"}}
226 #set($a = 12)
227 #set($b = 28)
228
229 #if($a < $b)
230 A is inferior
231 #else
232 B is inferior
233 #end
234
235 #if($a < 20 && $b > 17)
236 A is inferior than 20 AND B is superior than 17
237 #end
238
239 #if($a == 15 || $b <= 2)
240 A equals 15 OR B is inferior than 2 or equal
241 #end
242 {{/code}}
243
244 === Examples (bis) ===
245
246 {{code language="velocity"}}
247 #set($c = true)
248
249 #if($c)
250 C is true
251 #end
252
253 #if($doc.isNew())
254 The document is New
255 #else
256 The document is an old document
257 #end
258
259 #if(!$doc.isHidden())
260 The document is NOT hidden
261 #end
262 {{/code}}
263
264 === Lists ===
265
266 * You can create a list of objects.
267
268 {{code language="velocity"}}
269 #set($myList = ['My first Item', 'My Second Item', 'My third item'])
270 {{/code}}
271
272 * You can add a new element in the list:
273
274 {{code language="velocity"}}
275 $myList.add('My fourth item')
276 {{/code}}
277
278 * You can know how many objects are inside the list:
279
280 {{code language="velocity"}}
281 $myList.size()
282 {{/code}}
283
284 * You can ask if an object is inside the list
285
286 {{code language="velocity"}}
287 $myList.contains('My Second Item') ## which tells me 'true' or 'false'
288 {{/code}}
289
290 === Example of lists ===
291
292 {{code language="velocity"}}
293 $doc.getComments() ## will give all the comments of the current page !
294 $doc.getAttachmentList() ## will give all the attachments of the current page
295 $xwiki.getSpaces() ## will give the list of the different spaces of the wiki
296 {{/code}}
297
298
299 How could I know the number of spaces in the wiki?
300
301 {{code language="velocity"}}
302 ...
303 {{/code}}
304
305
306 How could I know if the space 'BlaBla' exists?
307
308 {{code language="velocity"}}
309 ...
310 {{/code}}
311
312
313 {{image reference="teacher.jpg"/}}
314
315 === Example of lists ===
316
317 {{code language="velocity"}}
318 $doc.getComments() ## will give all the comments of the current page !
319 $doc.getAttachmentList() ## will give all the attachments of the current page
320 $xwiki.getSpaces() ## will give the list of the different spaces of the wiki
321 {{/code}}
322
323
324 How could I know the number of spaces in the wiki?
325
326 {{code language="velocity"}}
327 $xwiki.getSpaces().size()
328 {{/code}}
329
330
331 How could I know if the space 'BlaBla' exists?
332
333 {{code language="velocity"}}
334 $xwiki.getSpaces().contains('BlaBla')
335 {{/code}}
336
337
338 {{image reference="goodmark.jpg"/}}
339
340 === Foreach ===
341
342 * How can I display all the elements of a list in a nice way?
343 ** Use the //#foreach// loop, son.
344 * Example:
345
346 {{code language="velocity"}}
347 This is the list of all the spaces of the wiki
348 #set($spaceList = $xwiki.getSpaces())
349 #foreach($space in $spaceList)
350 * $space
351 #end
352 {{/code}}
353
354 * Results:
355 {{image reference="foreach1.png"/}}
356
357 == The API ==
358
359 === ===
360
361 * XWiki offers a lot of objects with a lot of methods, to perform a lot of things !
362 ** Delete a document, add a tag to an other document, display the list of all blog entries, handle complex formulars, etc...
363 * This objets & methods are called the **API** (as //Application Programming Interface//).
364 * But how can I know what are theses objects and how to use it?
365
366 {{image reference="API.jpg"/}}
367
368 === By using the XWiki Script Reference Documentation (SRD) ===
369
370 {{image reference="SRD.png"/}}
371
372 [[http:~~/~~/platform.xwiki.org/xwiki/bin/view/SRD/Navigation?xpage=embed>>doc:platform:SRD.Navigation||queryString="xpage=embed"]]
373
374 === SRD ===
375
376 * The left column lists **all the XWiki special variables that make the API**.
377 * Select one of them, and you will have **all the methods this special variable offers**
378 ** Examples:
379 *** //$xwiki// offers a method //getDocument()//
380 *** //$doc// has a method //addAttachment()//
381 *** etc...
382
383 === Is the API a mess? ===
384
385 * While looking at the SRD, we can ask youself //"how many special variables is there?"//
386 * When we create a variable for our own usage, we have to be sure first to not call it as an existing special variable.
387 ** It's a mess!!!
388
389 {{image reference="mess.jpg"/}}
390
391 === Introducing Script Services ===
392
393 * In order to make the things cleaner, the plan is to remove a lot of this special variables and replace them by //script services//.
394 * Script services will become the only API in future.
395 * All script services are prefixed by //$services//.
396
397 {{image reference="datacenter.jpg"/}}
398
399 === ===
400
401 * To use a script service, you do it this way:
402
403 {{code language="velocity"}}
404 $services.query ## to perform complicated researchs
405 $services.localization ## to take care of the languages
406 $services.officeimporter ## to import office documents
407 ...
408 {{/code}}
409
410 * Of course, it is documented on the SRD!
411
412 {{image reference="wayne.jpg"/}}
413
414 === ===
415
416 * Sometime, you have different ways to do the same thing:
417 ** Using an old method (which may be declared as //deprecated//).
418 ** Using a script service instead
419 * ** Always perfers to use Script Service instead of deprecated APIs!!!**
420
421 {{code language="velocity"}}
422 $xwiki.searchDocument() ## allow us to perfom a query with the HQL language
423 ## now please use:
424 $services.query.hql() ## allow us to perfom a query with the HQL language
425 ## or even better:
426 $services.query.xwql() ## XWQL language is easier to use
427 {{/code}}
428
429 * Because it's the future!
430
431 {{image reference="future.jpg"/}}
432
433 == Manipulation of XObjects ==
434
435 === What is an XObject ? ===
436
437 * An //XObject// is an **object** that you can **save** in the wiki.
438 * An XObject is attached on a document, and you can see them with the "objects editor" on the wiki.
439
440 {{image reference="edit_objects.png"/}}
441
442 === ===
443
444 {{image reference="objects.png"/}}
445
446 === XClass ===
447
448 * An //XClass// is a //class// (a //description//) for XObjects.
449 ** You can define them using the class editor.
450 ** Or by using //Application Within Minutes//!
451
452 === Class Editor ===
453
454 {{image reference="class_editor.png"/}}
455
456 === Application Within Minutes ===
457
458 {{image reference="appwithinminutes.png"/}}
459
460 === Why using XClass and XObjects? ===
461
462 * It allows us to store **structured** informations.
463 ** A //Blog Post// (with a //title//, a //date//, a //content//, etc...)
464 ** An //Evaluation document// (with a //remark// for each //category//, a //mark//, etc...)
465 ** An //Holiday Request// (with //dates//, //status//, etc...)
466
467 * So the //information// is not lost in a giant document that holds only a big text...
468 ** And you can create //Applications//!
469
470 === XClass is used //everywhere// ===
471
472 * Almost everything in XWiki is an XClass and stored as XObjects!
473 ** //Users//
474 ** //Groups//
475 ** //Comments//
476 ** //Tags//
477 ** //Access Rights//
478 ** ....
479 * Learn to use //XClass// and you can **control all your wiki**.
480
481 === A comment is an XObject ===
482
483 {{image reference="comments.png"/}}
484
485 === A user is an XObject ===
486
487 {{image reference="user.png"/}}
488
489 === How to get an XObject with Velocity? ===
490
491 {{code language="velocity"}}
492 ## First, get the object
493 #set($object = $doc.getObject('XWiki.XWikiUsers'))
494 ## The parameter is the name of the class of the object you want to have
495 ## (a document can hold multiple objects of different classes)
496 ## The class name is the Document name where the class is defined
497
498 ## Display a parameter:
499 $object.display('first_name', 'view')
500 ## the parameter is the name of the field you want to display
501 ## if you are in "edit" mode, an HTML field will be displayed instead of the object value.
502
503 ## Set values:
504 $object.set('last_name', 'Bond')
505 $object.set('first_name', 'James')
506
507 ## Then save the document if you want your changes to be conserved
508 ## (you can add a comment when you save)
509 $doc.save('I have changed the name of the user.')
510 {{/code}}
511
512 === You can rollback what your script have done ===
513
514 {{image reference="rollback.png"/}}
515
516 == Tips ==
517
518 === How to get an other document? ===
519
520 * In the past, we used to do:
521
522 {{code language="velocity"}}
523 #set($document = $xwiki.getDocument('Space.Page'))
524 {{/code}}
525
526 * But it's not good, because what if the page name has a dot?
527
528 {{code language="velocity"}}
529 #set($document = $xwiki.getDocument('Space.Pa.ge'))
530 ## ??? What is the Space ? What is the Page ?
531 {{/code}}
532
533 * And what will happen if the document name have accents or weird characters?
534
535 === Solution: use references ! ===
536
537 {{code language="velocity"}}
538 #set($reference = $services.model.createDocumentReference('Wiki', 'Space', 'Page'))
539 #set($document = $xwiki.getDocument($reference))
540 {{/code}}
541
542 * It is better! The reference tool allow us to strictly separe what is the space and what is the page
543 * And the reference tool will take care of weird characters !
544
545 {{code language="velocity"}}
546 #set($reference = $services.model.createDocumentReference('Wiki', 'Space', 'Pa.ge'))
547 #set($document = $xwiki.getDocument($reference))
548 ## Not a problem!!!
549 {{/code}}
550
551 === References ===
552
553 * You can get create references for documents in other wikis :
554
555 {{code language="velocity"}}
556 #set($reference = $services.model.createDocumentReference('Wiki', 'Space', 'Page'))
557 {{/code}}
558
559 * If you want to get a document in the current wiki, you can set an empty parameter:
560
561 {{code language="velocity"}}
562 #set($reference = $services.model.createDocumentReference('', 'Space', 'Page'))
563 ## the reference point a document in the current wiki
564 {{/code}}
565
566 === Use case: changing the name of a user ===
567
568 {{code language="velocity"}}
569 ## First, create a reference to his user page
570 #set($reference = $services.model.createDocumentReference('', 'XWiki', 'ldubost'))
571 ## Then, get its document
572 #set($document = $xwiki.getDocument($reference))
573 ## Then, get the 'User' object
574 #set($object = $document.getObject('XWiki.XWikiUsers'))
575 ## Then change his name
576 $object.set('first_name', 'Harry')
577 $object.set('last_name', 'Potter')
578 ## And save the document
579 $document.save()
580 {{/code}}
581
582 === But remember we know who changes what! ===
583
584 {{image reference="history.png"/}}
585
586 (% style="text-align: right; margin-top: 20px;" %)
587 "//I have your name and I know where you live...//"
588
589 == Going further ==
590
591 === ===
592
593 * See the [[Velocity documentation>>http://velocity.apache.org/]] to have more details about the language itself
594 * See the [[XWiki Script Guide>>doc:Documentation.DevGuide.Scripting.WebHome]] to have some informations about how to make scripts in XWiki
595 * See the [[XWiki Query Module>>doc:extensions:Extension.Query Module]] to learn how to do advanced queries
596 * See the [[XWiki Data Model>>doc:Documentation.DevGuide.DataModel]] to learn how to create your XWiki classes
597
598 **But in general:**
599
600 * practice and ask for help!!!
601
602 === ===
603
604 * I hope you now have a better idea of what Velocity is and how you can use it in XWiki.
605
606 {{image reference="velocity.jpg"/}}

Get Connected