Customizing OpenCms Site
From ThemesWiki
| Official Page |
| Project Documentation |
| Download |
|
This tutorial will explain you how to develop the look and feel of published content adding dynamic elements and controlling resources. http://responsabile-91.pilotpressltd.com responsabile http://legione-21.pilotpressltd.com/node/legione-mobile-ettore-muti/ legione mobile ettore muti http://pellegrino-34.pilotpressltd.com/fedrica-pellegrinofeed-rss/ fedrica pellegrinofeed rss http://tibetani-79.pilotpressltd.com tibetani http://woodworking-60.pilotpressltd.com/second-hand-woodworking-machines/ second hand woodworking machines http://massive-92.pilotpressltd.com/2008/07/massive-mature/ massive mature http://remember-67.pilotpressltd.com/wordpress/remember-cosmic/ remember cosmic http://estensibili-23.pilotpressltd.com/inferriate-estensibili/ inferriate estensibili http://sylvie-13.pilotpressltd.com/sylvie-nerval-versione-italiana/ sylvie nerval versione italiana http://ritardante-73.pilotpressltd.com/2008/07/02/ritardante-golden-tao/ ritardante golden tao http://tecnologico-78.pilotpressltd.com/2008/08/nuovo-polo-tecnologico-vicenza/ nuovo polo tecnologico vicenza http://installazioni-68.pilotpressltd.com/blog/entry/installazioni-impianto-spa/ installazioni impianto spa http://uvetta-60.pilotpressltd.com uvetta http://costitutivo-59.pilotpressltd.com/atto-costitutivo-associazione-musicale/ atto costitutivo associazione musicale http://anticipo-84.pilotpressltd.com/wordpress/modulistica-anticipo-tfr/ modulistica anticipo tfr http://patrimonio-76.pilotpressltd.com/2008/07/comune-roma-patrimonio-it/ comune roma patrimonio it http://unione-23.pilotpressltd.com/wordpress/verbale-di-riunione/ verbale di riunione http://aljazeera-38.pilotpressltd.com/2008/07/aljazeera-sport-channel/ aljazeera sport channel http://forumgratis-36.pilotpressltd.com/blog/entry/forumgratis-biz/ forumgratis biz http://uguali-76.pilotpressltd.com/2008/07/21/lima-wire-progrmmi-uguali/ lima wire progrmmi uguali http://agnano-63.pilotpressltd.com/node/mercedes-benz-agnano/ mercedes benz agnano http://istanbul-29.pilotpressltd.com istanbul http://legione-21.pilotpressltd.com/node/legione-inverno/ legione inverno http://regala-38.pilotpressltd.com/regalare-disco/ regalare disco http://gallarate-83.pilotpressltd.com/node/cartina-di-gallarate/ cartina di gallarate http://murphy-27.pilotpressltd.com/2008/08/carolyn-murphy-brandon-boyd/ carolyn murphy brandon boyd http://filippo-74.pilotpressltd.com/2008/06/tema-filippo-ii/ tema filippo ii http://consenso-43.pilotpressltd.com/node/consenso-privacy-modulo/ consenso privacy modulo http://condizioni-68.pilotpressltd.com/2008/06/condizioni-metereologiche/ condizioni metereologiche http://secrets-60.pilotpressltd.com/2008/07/school-boy-secrets/ school boy secrets http://spiral-42.pilotpressltd.com/2008/06/dowload-tekno-spiral-tribe/ dowload tekno spiral tribe http://recipienti-64.pilotpressltd.com/2008/08/09/recipienti-semplici-pressione/ recipienti semplici pressione http://andare-4.pilotpressltd.com/blog/entry/andare-meta/ andare meta http://desnudos-96.pilotpressltd.com/2008/07/desnudos-guapos/ desnudos guapos http://passeggeri-53.pilotpressltd.com/node/dato-aereo-traffico-passeggeri/ dato aereo traffico passeggeri http://frontera-53.pilotpressltd.com/2008/07/07/vendo-frontera-sport/ vendo frontera sport http://autonomi-71.pilotpressltd.com/2008/08/prestito-ad-autonomi/ prestito ad autonomi http://ipotecaria-64.pilotpressltd.com/blog/entry/iscrizione-ipotecaria/ iscrizione ipotecaria http://comparison-78.pilotpressltd.com/wordpress/airgun-comparison/ airgun comparison http://dirisio-42.pilotpressltd.com/node/luca-dirisio-wallpaper/ luca dirisio wallpaper http://pittorico-70.pilotpressltd.com/blog/entry/stile-pittorico-caravaggio/ stile pittorico caravaggio http://angelica-58.pilotpressltd.com/blog/entry/chiesa-evangelica-frascati/ chiesa evangelica frascati http://violazioni-55.pilotpressltd.com/blog/entry/violazioni-sicurezza-cantiere/ violazioni sicurezza cantiere http://fumare-78.pilotpressltd.com/2008/08/07/fumare-uccide/ fumare uccide http://modugno-74.pilotpressltd.com/wordpress/testi-domenico-modugno/ testi domenico modugno http://settore-71.pilotpressltd.com/tranciature-settore-automobilistico-milano/ tranciature settore automobilistico milano http://costitutivo-59.pilotpressltd.com/atto-costitutivo-comitato/ atto costitutivo comitato http://campionato-87.pilotpressltd.com/wordpress/campionatori-diffusione/ campionatori diffusione http://casciano-22.pilotpressltd.com/2008/07/san-casciano-terme-agriturismo/ san casciano terme agriturismo http://genera-94.pilotpressltd.com/2008/07/direttori-generali/ direttori generali
http://tiziano-26.pilotpressltd.com/blog/entry/tiziano-ferro-site-unofficial/ tiziano ferro site unofficial http://chiudere-8.pilotpressltd.com/wordpress/chiudere-lavoro-all-uncinetto/ chiudere lavoro all uncinetto http://network-62.pilotpressltd.com/2008/08/gestione-networking-rete/ gestione networking rete http://esoterici-98.pilotpressltd.com/blog/entry/torino-esoterica-gustavosimbolo-esoterici/ torino esoterica gustavosimbolo esoterici http://termine-56.pilotpressltd.com/operazione-pronto-conto-termine/ operazione pronto conto termine http://brembana-9.pilotpressltd.com/wordpress/valle-brembana-web/ valle brembana web http://comparison-78.pilotpressltd.com/wordpress/refinance-comparison/ refinance comparison http://meteorologico-98.pilotpressltd.com/node/centro-meteorologico/ centro meteorologico http://infermieristica-43.pilotpressltd.com/wordpress/cartella-infermieristica/ cartella infermieristica http://banking-94.pilotpressltd.com/node/corporate-banking-pubblica-amministrazione/ corporate banking pubblica amministrazione http://disponibilita-76.pilotpressltd.com/disponibilita-cane-razza-pedigree/ disponibilita cane razza pedigree http://igiene-97.pilotpressltd.com/node/pacchetto-igiene/ pacchetto igiene http://gattopardo-32.pilotpressltd.com/gattopardo-capo-vaticano/ gattopardo capo vaticano http://candid-34.pilotpressltd.com/wordpress/candido-voltaire-trama/ candido voltaire trama http://piemontese-70.pilotpressltd.com/tomino-piemontese/ tomino piemontese http://francis-87.pilotpressltd.com/blog/entry/voli-milano-san-francisco/ voli milano san francisco http://canaglie-81.pilotpressltd.com/2008/07/torneo-calcio-simpatica-canaglie/ torneo calcio simpatica canaglie http://openoffice-64.pilotpressltd.com/2008/07/it-openoffice-org/ it openoffice org http://lettini-57.pilotpressltd.com/blog/entry/lettini-alluminio/ lettini alluminio http://processo-18.pilotpressltd.com/wordpress/sigla-processo-biscardi/ sigla processo biscardi http://villaggio-54.pilotpressltd.com rray http://torrent-97.pilotpressltd.com/2008/07/21/cercare-torrent/ cercare torrent http://yellow-16.pilotpressltd.com/huns-yellow/ huns yellow http://magnetico-67.pilotpressltd.com magnetico http://slovakia-45.pilotpressltd.com/2008/07/30/slovakia-hockey-team/ slovakia hockey team http://agostino-77.pilotpressltd.com/wordpress/d-agostino/ d agostino http://capriate-83.pilotpressltd.com/node/schema-capriate-legno/ schema capriate legno http://salvaguardia-23.pilotpressltd.com/blog/entry/salvaguardia-opere-artistiche/ salvaguardia opere artistiche http://tibetani-79.pilotpressltd.com/2008/08/04/cembali-tibetani/ cembali tibetani http://combinatore-25.pilotpressltd.com/2008/07/01/antifurto-combinatore-gsm/ antifurto combinatore gsm http://discale-56.pilotpressltd.com/protesi-discale/ protesi discale http://silvano-98.pilotpressltd.com/wordpress/monolocale-fitto-montesilvano/ monolocale fitto montesilvano http://andare-4.pilotpressltd.com/blog/entry/foto-andare-bicicletta/ foto andare bicicletta http://yellow-16.pilotpressltd.com/the-hun-yellowpages/ the hun yellowpages http://marittimo-67.pilotpressltd.com/residence-marittimo-riccione/ residence marittimo riccione http://organizzativa-43.pilotpressltd.com/2008/07/28/autonomia-organizzativa-amministrativa/ autonomia organizzativa amministrativa http://davinci-68.pilotpressltd.com/node/davinci-wow-server-emulator/ davinci wow server emulator http://informativa-80.pilotpressltd.com/wordpress/privacy-informativa-al-personale/ privacy informativa al personale http://stellata-79.pilotpressltd.com/2008/06/notte-stellata-rodano/ notte stellata rodano http://romantico-6.pilotpressltd.com/wordpress/agriturismo-romantico-provincia-bologna/ agriturismo romantico provincia bologna http://santangelo-87.pilotpressltd.com/notaio-santangelo-enrico/ notaio santangelo enrico http://funzionale-28.pilotpressltd.com/2008/08/05/grammatica-funzionale-dik/ grammatica funzionale dik http://recapito-77.pilotpressltd.com/blog/entry/annuncio-recapito-telefonico/ annuncio recapito telefonico http://gbound-34.pilotpressltd.com/2008/08/16/gbound-bypass/ gbound bypass http://questo-31.pilotpressltd.com/questore-arrigo-molinari/ questore arrigo molinari http://lathes-17.pilotpressltd.com/node/used-lathes/ used lathes http://disponibilita-76.pilotpressltd.com/massima-disponibilita/ massima disponibilita http://getaway-59.pilotpressltd.com/wordpress/romantic-getaway-texas/ romantic getaway texas http://metereologico-70.pilotpressltd.com/blog/entry/servizio-metereologico/ servizio metereologico http://inland-19.pilotpressltd.com/wordpress/dizionario-finlandese-on-line/ dizionario finlandese on line
http://mastroianni-55.pilotpressltd.com/node/flora-mastroianni/ flora mastroianni http://attraverso-78.pilotpressltd.com/apprendere-attraverso-gioco/ apprendere attraverso gioco http://puntamento-63.pilotpressltd.com/2008/07/ospedale-gallarate-appuntamento-dentistici/ ospedale gallarate appuntamento dentistici http://biasia-99.pilotpressltd.com/2008/08/12/biasia-borsa/ biasia borsa http://recipienti-64.pilotpressltd.com/2008/08/06/rivestimento-metallo-recipienti/ rivestimento metallo recipienti http://stellata-79.pilotpressltd.com/2008/06/magnolia-stellata/ magnolia stellata http://consultazione-77.pilotpressltd.com/blog/entry/consultazione-libri/ consultazione libri http://melita-39.pilotpressltd.com/forum-melita-toniolo/ forum melita toniolo http://svizzero-90.pilotpressltd.com/2008/08/foto-grande-bovaro-svizzero/ foto grande bovaro svizzero http://mancata-34.pilotpressltd.com/wordpress/mancata-convocazione-giurisprudenza/ mancata convocazione giurisprudenza http://tascabile-15.pilotpressltd.com/blog/entry/guide-turistiche-tascabile/ guide turistiche tascabile http://discreet-57.pilotpressltd.com/blog/entry/discreet-sexdiscrete-sex/ discreet sexdiscrete sex http://karolina-61.pilotpressltd.com/karolina-kourkovakarup-s/ karolina kourkovakarup s http://encoder-12.pilotpressltd.com/wordpress/windows-media-encoder/ windows media encoder http://festivo-69.pilotpressltd.com/node/straordinario-festivo/ straordinario festivo http://reparto-72.pilotpressltd.com/2008/06/21/esercizio-preparto/ esercizio preparto http://animal-38.pilotpressltd.com/2008/07/appartamento-formentera-animale-ammessi/ appartamento formentera animale ammessi http://alberti-14.pilotpressltd.com/de-pictura-alberti/ de pictura alberti http://premiata-39.pilotpressltd.com/blog/entry/premiata-forneria-marconi/ premiata forneria marconi http://funeral-68.pilotpressltd.com funeral http://fotografico-96.pilotpressltd.com/archivio-fotografico-caterina-balivo/ archivio fotografico caterina balivo http://forumgratis-36.pilotpressltd.com/blog/entry/lostitalia-forumgratis-com/ lostitalia forumgratis com http://mondiali-7.pilotpressltd.com/node/mondiali-calcio-sito-ufficialemondochat/ mondiali calcio sito ufficialemondochat http://recapito-77.pilotpressltd.com/blog/entry/seab-biella-recapito/ seab biella recapito http://parodi-71.pilotpressltd.com/wordpress/capezzolo-cristina-parodi/ capezzolo cristina parodi http://consulti-21.pilotpressltd.com/2008/08/02/consulting-it-suggest-url/ consulting it suggest url http://settings-92.pilotpressltd.com/wordpress/smartmovie-settings/ smartmovie settings http://istruzione-68.pilotpressltd.com/wordpress/istruzione-compilazione-questionario/ istruzione compilazione questionario http://serrenti-39.pilotpressltd.com/wordpress/hotel-serrenti/ hotel serrenti http://gordon-72.pilotpressltd.com/continued-fractions-rogers-gordon/ continued fractions rogers gordon http://positions-4.pilotpressltd.com/node/positions-sex/ positions sex http://marittimo-67.pilotpressltd.com/raccomandatario-marittimo/ raccomandatario marittimo http://premium-99.pilotpressltd.com/node/craccare-mediaset-premium/ craccare mediaset premium http://gaulle-14.pilotpressltd.com/wordpress/c-de-gaulle/ c de gaulle http://bonnie-34.pilotpressltd.com/bonnie-dalzell-borzoicantante-bono/ bonnie dalzell borzoicantante bono http://mosconi-3.pilotpressltd.com/vespa-germanicagermano-mosconi/ vespa germanicagermano mosconi http://playhouse-1.pilotpressltd.com/2008/07/28/playhouse-disney-it/ playhouse disney it http://berchidda-37.pilotpressltd.com/node/autonoleggio-berchidda/ autonoleggio berchidda http://cucire-35.pilotpressltd.com/macchina-da-cucire-usata/ macchina da cucire usata http://cannero-19.pilotpressltd.com/cerco-lavoro-cannero-riviera/ cerco lavoro cannero riviera http://cruiser-91.pilotpressltd.com/motore-mercruiser-revisionato/ motore mercruiser revisionato http://pancia-12.pilotpressltd.com/2008/07/dieta-pancia-piatta/ dieta pancia piatta http://interim-43.pilotpressltd.com/blog/entry/interim-mechelen/ interim mechelen http://miscela-98.pilotpressltd.com miscela http://dresses-37.pilotpressltd.com/wordpress/formal-dresses/ formal dresses http://disinstallazione-19.pilotpressltd.com/wordpress/disinstallazione-window-xp/ disinstallazione window xp http://igiene-97.pilotpressltd.com/node/dispense-igiene-alimenti-haccp/ dispense igiene alimenti haccp http://platonico-55.pilotpressltd.com/citazione-amore-platonico/ citazione amore platonico http://sannia-52.pilotpressltd.com/2008/06/25/fitoterapia-sannia/ fitoterapia sannia http://trionfo-6.pilotpressltd.com trionfo
Contents |
[edit] Working with Templates
As we have seen, JSP tags, tag libraries and scriptlets provide a method of mixing dynamic content into HTML (or XML) documents. Their main use in OpenCms is for OpenCms templates. Using JSP tags, we will be able to create templates that generate navigation information, fetch content, and do other things to make our OpenCms website attractive and compelling for visitors.
We will start by creating a place where we can store our new templates.
[edit] Template Module
Modules are a mechanism for extending the functionality of OpenCms. Sophisticated modules can provide integration with other products, modify OpenCms itself, or extend the capabilities of OpenCms. But they can also be used for more humble tasks.
As we begin working with templates, we will need a place to store the template files. It is desirable to keep templates out of the content portion of OpenCms. Content editors don't need to see templates, nor do we want functional components cluttering up the space we use for managing content. Also, it is often useful to be able to move the templates (along with images, stylesheets and supporting files) from one OpenCms server to another without having to move all of the content. For these reasons, it can be very useful to store templates in their own module.
I assume that you have created a new module, and we will now use this module as a place to organize and store our new templates.
To get to this module in the explorer view of the OpenCms Workplace, you will first need to change sites. From the Site drop-down list, choose / instead of /sites/default/. You should now be able to navigate to your module in the /system/modules folder in the navigation pane on the left.
The module created is assumed to be named tv.alephnull.modules.templates, and there is a folder for this module called /system/modules/tv.alephnull.modules. templates. Within this folder, there should be at least three subfolders templates, elements, and resources. Each of these three folders will store a particular kind of data:
-
templates: This folder will contain the JSP template files. -
elements: This folder will contain JSP files (or text files) that the template may use. -
resources: This folder will contain stylesheets, images, and other files that the client will need.
If these folders do not already exist (which may happen if, for example, the appropriate checkboxes where not checked during module creation), then you can just create them.
Modules may have other folders at this level, including the classes and libs folders for housing compiled Java classes, and the default_bodies folder for storing information on the body layout for a given piece of content. But we do not need these folders here.
In OpenCms 5.0 there were two folders for templates jsptemplates for JSP templates and templates for XML templates. In OpenCms 6, JSP templates now go into the templates folder. XML templates are no longer used (unless you install legacy support for them). However, you may sometimes still see the folder jsptemplates used in modules often for housing so-called "hidden" templates that editors cannot use directly.
Some folders, such as templates, are explicitly referenced by OpenCms code. This is not the case for the resources and elements folders. Their naming and use, though, is a convention encouraged by the OpenCms development community, so while there is no requirement to create these folders, or even to structure your module the way we are doing it here, you are encouraged to follow the established convention.
Now that we have the necessary folders, we can create our first template.
[edit] Creating a New Template
The first thing we will do is create a new JSP page. To do this, navigate to the template folder of the module, and click on the New button (with the magic wand icon) to create a new file. Choose JSP from the list and continue. The first thing you will need to do is give the new JSP a name.
Next, you will be prompted to edit the properties of the file:
You will definitely want to set the Title field to something distinct. OpenCms displays the title of a template in the template drop-down list that content creators will see when creating a new file.
The cache field allows you to set specific caching properties, which determine how the template is stored in the OpenCms FlexCache. Usually, it is best to leave this blank.
The content‑encoding field allows you to specify a particular type of content encoding (ISO‑8859 or UTF‑8 for example). You only need to set this when the encoding of the template is different from the default encoding for OpenCms and the content that will be rendered in this template (that is the Page files) will also use this content encoding. In short, you will probably not need to give this field a value.
The last field is called export. This determines whether the template will be exported the first time it is accessed. By default, its value is false. If this value is true, then the template will only be executed once, and the resulting HTML will be stored on disk. When it is next requested, the static HTML will be served, and the JSP will not be executed again.
This is useful where the server is under high load and the contents of the template are not particularly time sensitive. Usually, you will want the template file to be executed every time the file is accessed so that you will want to leave the export field set to its default value, false.
Clicking Finish will create the template file and return you to the explorer view, where you should now see your new template file. Click on the file's icon and choose Edit sourcecode to edit the new template.
[edit] The JSP Template
The template will provide the layout for the contents of any associated pages. A template can include JSP tags and scriptlets, and it can also import other JSP files. In this section, we will create a simple JSP template. In subsequent sections, we will expand this template.
Here is an example of a very simple JSP template. It creates a basic HTML document and puts the contents of the requested file into the main body of the page.
<%@ page session="false" %> <%@ taglib prefix="cms" uri="http://www.opencms.org/taglib/cms" %> <!DOCTYPE html public "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title><cms:property name="Title" escapeHtml="true"/></title> </head> <body> <h1><cms:property name="Title" escapeHtml="true"/></h1> <cms:include element="text1"/> </body> </html>
The first two lines contain basic JSP tags that you are very likely to need in all of your templates. The page tag instructs the JSP engine not to create a session object. While some applications will require session objects, this one will not, and we can speed things up by not tracking sessions.
As we saw earlier in this tutorial, the taglib tag tells the server that we are using the OpenCms tag library (whose URI is http://www.opencms.org/taglib/cms) and that any elements with the cms prefix will be from this tag library.
Most of the template is simply HTML. Only the tags prefaced with cms are interpreted by the JSP engine. The rest are sent "as is" to the client. In this template, there are only two elements from the OpenCms tag library. The property tag occurs twice once to include the Title of the page as the contents of the HTML title element and once to include the Title of the page inside the h1 element. Let's take a closer look at this tag:
<cms:property name="Title" escapeHtml="true"/>
The prefix cms instructs the server to use the element property from the OpenCms tag library (because the taglib tag tells the server that any elements with the cms prefix will be from this tag library). The property element in the OpenCms tag library provides access to the properties of the requested document.
The property tag has three attributes name, file, and escapeHtml. The name attribute indicates that the property we want to access is called Title. The values of attributes are case sensitive you cannot, for example, have title instead of Title.
The attribute escapeHtml, which is set to true, instructs the JSP interpreter to escape any HTML tags that exist in that property. For example, if the title of the page was "Using the <pre/> tag", it would be converted to "Using the >pre/< tag". This prevents the contents of a property accidentally being interpreting as HTML.
The file attribute allows you to specify the name of the file whose properties you are trying to access. If no file is specified, as happens in this example, then the properties of the current file are used.
You can view all the properties for a file by locating the file in the explorer view, clicking on the file's icon, and selecting Properties from the popup menu.
The second OpenCms JSP tag used in the example above is the include tag:
<cms:include element="text1"/>
This tag gets the contents of the requested file and puts them inside the template for delivery to the client. Here, things get a little more complicated.
Each Page file in the VFS is stored inside a special XML file that describes the document. This XML file may include content in different languages, and it may have several different subsections. For example, some Page documents can have several "sub-documents" nested inside of them. These sub-documents are called elements. By default, these elements are named according to a standard convention, where the first is text1, and each subsequent element just increments the digit at the end text2, text3, and so on.
By default, when we create new documents, we are only creating the first element, text1, so for this basic template, we just want to display the first (default) section of the requested document. The include tag is used to specify the element that we want to display by setting the value of the element attribute to "text1".
The element attribute is required. When using the OpenCms include tag, you must specify a particular element otherwise, OpenCms will generate a NullPointerException when it tries to load the template.
Once this new template is saved, we can test it out.
[edit] Testing the New Template
Choose /sites/default from the Site drop-down list in the explorer view, and navigate back to the playground folder that was earlier created. We will create a new file in this folder that uses the new template.
Click on the New button in the explorer toolbar and select Page from the list of file types. The next screen will prompt us to name the file and set a few crucial properties, including which template the page will use.
The new template should be available in the Template drop-down list.
How does this template get added to the Template drop-down list? OpenCms searches all the template folders in the modules and adds any file it finds to the template list. If the file has a Title property, that property is displayed here.
Once the name and template are set, continue on to the properties screen, set any desired properties, and click Finish.
We are now back in the explorer view looking at the new file. Now click the file's icon and choose Edit page to add some content to the file.
Once we have some text in the file, we can save the file and test the template. From the explorer view, we can click on the file's name to see a preview of the file. The preview will open in a new window and should look something like this:
Here is what the output looks like in HTML:
<!DOCTYPE html public "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>Testing Example Template</title> </head> <body> <h1>Testing Example Template</h1> This is some example content. We are using it to test a new template. </body> </html>
The two property tags have been replaced by the title of the document, and the include tag has been replaced with the contents of our page.
We will now make a few improvements to the template. First, we will create a stylesheet for our template.
[edit] Using Resources in a Template
Earlier, we created a resources folder for our module. This is where stylesheets, JavaScript files, and images are stored. Right now, let's create a stylesheet in the resources folder.
A stylesheet is composed of plain text, so when we create a new file, it needs to be of type Text. We will name the new file main.css. Once the file is created, we can edit it:
/*
* Cascading Style Sheet for Example OpenCms Templates
*/
h1 {
color: navy;
}
body {
font-family: serif;
}
This is a very basic stylesheet that will change the color of the contents of the h1 element to navy blue and will set the default font of anything in the body element to the browser's default serif font.
Now we need to insert this into the template:
<%@ page session="false" %> <%@ taglib prefix="cms" uri="http://www.opencms.org/taglib/cms" %> <!DOCTYPE html public "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title><cms:property name="Title" escapeHtml="true"/></title> <code><link type="text/css" rel="stylesheet"</code> href="<cms:link>/system/modules/tv.alephnull.modules.templates/resources/main.css</cms:link>"/> </head> <body> <h1><cms:property name="Title" escapeHtml="true"/></h1> <cms:include element="text1"/> </body> </html>
The only addition is the link tag (which is nested within the href parameter). This tag takes the VFS path of a file, and converts it into a URI that the web browser can use to request the resource. Any time you are referencing a VFS file in an OpenCms template, you should use the OpenCms link tag (cms:link). We will look at this tag later.
[edit] Making a File Editable
In OpenCms 6.2, you can configure the template to allow logged-in and authorized users the ability to edit a file on the spot. This is called "direct edit". With direct editing, when a content editor is logged in and viewing the site, she or he will see buttons that, when clicked, allow them to edit the resource right there, without having to go through the OpenCms Workplace.
This feature is enabled in the template file. To add it, you will need to add one line and modify one line:
<%@ page session="false" %> <%@ taglib prefix="cms" uri="http://www.opencms.org/taglib/cms" %> <!DOCTYPE html public "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title><cms:property name="Title" escapeHtml="true"/></title> <link type="text/css" rel="stylesheet" href="<cms:link>/system/modules/tv.alephnull.modules.templates/resources/main.css</cms:link>"/> <cms:editable/> </head> <body> <h1><cms:property name="Title" escapeHtml="true"/></h1> <cms:include element="text1" editable="true"/> </body> </html>
The first highlighted line, located in the head, contains the editable tag from the OpenCms tag library. This tag instructs OpenCms to load the editing CSS and JavaScript files.
The second highlighted item is the include tag from the OpenCms tag library. The only change to this is the addition of the editable attribute, which has the value true. This tells OpenCms to allow this particular piece of content to be edited with the direct edit feature.
Now, when we view the test file (in the /playground folder), it looks like this:
Clicking on the target button on the right side will load the content editor:
To disable the direct edit feature, simply remove the editable attribute from the include tag. For good measure, you should probably remove the editable tag as well, but that is not necessary.
Next, we will look at loading data stored in other JSP files into the template.
[edit] External Elements
Sometimes it is useful to store parts of the template in separate files. You might want to do this to reduce clutter in the template, or you might want to do this so that one particular piece of template code can be used by multiple templates.
Code that generates navigation is frequently needed and often reused. Unfortunately, there is no JSP tag to do this, so we will have to resort to a scriptlet. However, by putting this scriptlet into its own file, we can re-use it in multiple templates.
The best place to store these files is in the module's elements folder. We'll create a JSP file in that folder called navigation.jsp. This file will be a short scriptlet.
[edit] A Short Scriptlet
The following scriptlet fetches the navigation information from OpenCms and then prints it out. This cannot be done with JSP tags. Otherwise, we would create our navigation that way.
If you are not a Java programmer, you can feel free to skip this section, or you may want to copy the code and use it in your own applications. After the code, there will be a brief explanation.
The contents of the file look like this:
<%@ page session="false"
import="java.util.Iterator,
java.util.List,
org.opencms.jsp.CmsJspNavBuilder,
org.opencms.jsp.CmsJspNavElement,
org.opencms.jsp.CmsJspActionElement"
%>
<%
/*
* Provides basic site navigation.
*/
// Create the class from which we will get navigation.
CmsJspActionElement cms =
new CmsJspActionElement( pageContext, request, response );
// Get navigation info
CmsJspNavBuilder navigation = cms.getNavigation();
List navItems = navigation.getNavigationForFolder();
Iterator i = navItems.iterator();
// Loop through all of the items in the ArrayList and print the
// menu.
while( i.hasNext() ) {
CmsJspNavElement navElement = ( CmsJspNavElement )i.next();
String link = cms.link( navElement.getResourceName() );
String title = navElement.getTitle();
out.println("»<a href=\"" + link + "\">" + title + "</a><br/>");
}
%>
This scriptlet looks fairly daunting. In fact, it uses many important features of the OpenCms scriptlet API, but it is actually quite simple.
Let's break it down into smaller chunks and examine how it works.
The page tag imports all the Java classes that will be needed. Those whose names begin with java. are built into the Java programming language. Those whose names begin with org.opencms. are OpenCms Java classes.
<%@ page session="false" import="java.util.Iterator, java.util.List, org.opencms.jsp.CmsJspNavBuilder, org.opencms.jsp.CmsJspNavElement, org.opencms.jsp.CmsJspActionElement" %>
The next thing we do is create a CmsJspActionElement object named cms. This object provides access to the OpenCms navigation information.
CmsJspActionElement cms = new CmsJspActionElement( pageContext, request, response );
Once this object has been created, we need to get the navigation information from it. This is done in the next three lines:
CmsJspNavBuilder navigation = cms.getNavigation(); List navItems = navigation.getNavigationForFolder(); Iterator i = navItems.iterator();
The first line gets a CmsJspNavBuilder object, which has all of the necessary information about navigation. We use the getNavigationForFolder method to get a list of all of the items in the current folder and store it in a variable called navItems. Once we have the list, we need an Iterator object that will allow us to walk through the list in order.
Now we are ready to go through the list, one item at a time, and print out the navigation links:
while( i.hasNext() ) {
CmsJspNavElement navElement = ( CmsJspNavElement )i.next();
String link = cms.link( navElement.getResourceName() );
String title = navElement.getTitle();
out.println("»<a href=\"" + link + "\">" + title +
"</a><br/>");
}
While there are more items, this code will:
- Get the navigation element, which stores information about a particular file (line 2).
- Create a link for that file (line 3).
- Get the title of that file (line 4).
- Print out a hyperlink that points to that file (line 5). Don't get too distracted by all of the quotes and backslashes in the
printlnmethod. The backslashes help Java understand which quotes need to get written to the HTML output.
That's all there is to it. All we need to do now is add it to the template.
The OpenCms documentation that comes bundled with OpenCms includes more documentation on working with the navigation objects. If you are interested in improving on this simple navigation script, you can start by looking there.
[edit] Including the Scriptlet in the Template
Now that we have a navigation scriptlet stored in the elements directory, how can use it in the template? A simple addition to our template will add navigation. Here is the template file, with the new addition highlighted:
<%@ page session="false" %> <%@ taglib prefix="cms" uri="http://www.opencms.org/taglib/cms" %> <!DOCTYPE html public "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title><cms:property name="Title" escapeHtml="true"/></title> <link type="text/css" rel="stylesheet" href="<cms:link>/system/modules/tv.alephnull.modules.templates/resources/main.css</cms:link>"/> <cms:editable/> </head> <body> <h1><cms:property name="Title" escapeHtml="true"/></h1> <div name="menu" style="float:left;border:1px solid gray;padding: 3px;"> <b>Menu</b><br /> <cms:include file="../elements/navigation.jsp"/> </div> <cms:include element="text1" editable="true"/> </body> </html>
The div element is just used to set the navigation off from the rest of the text. In fact, the only functional change above is the addition of the OpenCms include tag that points to the elements/navigation.jsp file.
If we view our test file again, it should have a navigation menu that looks something like this:
Our simple template has now grown a bit.
Next, we will explore the OpenCms tag library in more detail. Along the way, we will revisit some of the tags that we have used already, and we will discuss some new tags.
[edit] More on JSP Tags
We have looked at the basics of JSP and Scriptlets and even created a basic template using JSP tags. We will now look at JSP tags in more detail and at how they can be used within HTML documents.
[edit] JSP Directives
The JSP tag libraries use HTML-like (or XML-like) element syntax for including dynamic functionality in a document. Core JSP tags, or directives, are characterized by the percent sign, %.
For example, the JSP page directive from the JSP template earlier in this tutorial looked like this:
<%@ page session="false" %>
Core tags are used to provide information to the server about how the page is to be processed. So far, we've looked at the page directive, which provides the server with information on how to treat the page, and the taglib directive, which tells the server what JSP tag libraries will be used in the page.
A JSP expression' is' a Java statement that is converted to a string and automatically printed. JSP expressions also have a percent sign. The following JSP expression, for example, prints out the date and time:
Right now, it is <%= new java.util.Date() %>
[edit] New XML Syntax for Core JSP Tags
Recent developments in JSP technology, especially in version 1.2, encourage moving from the original JSP percent-style tag format to an XML-compliant syntax. Core tags have been redefined to use XML namespaces, using the jsp prefix instead of the percent-style notation. The new XML syntax is not completely supported by OpenCms. While you can sometimes get away with using it, you might want to consider a potential drawback.
The FlexCache mechanism stores JSP pages in the real file system, as well as the VFS, so that those pages can be executed by the servlet engine. When these files are moved from the VFS to the local file system, OpenCms must replace VFS path information with absolute file-system paths. To accomplish this, OpenCms scans the JSP files, trying to replace paths in tags that need replacement. However, this scanning mechanism does not understand all of the JSP tags in particular, it does not
understand any of the XML-style JSP tags. It ignores any tag that it cannot interpret. Consequently, XML-style tags that need path translation will be ignored. I will try to point out particular instances of this as we go through examples, and I will show examples of XML syntax when appropriate. But, if you choose to use the XML-style JSP syntax, be wary of tags that reference file-system paths.
The remainder of this book will use only the old syntax.
[edit] The OpenCms Tag Library
The OpenCms tag library is a built-in component of OpenCms. It provides access to the data managed by OpenCms and provides basic functions for presenting OpenCms data in a template. To begin this examination of the OpenCms tag library, we will return to the JSP template that we created earlier in this tutorial.
[edit] Breaking a JSP Template into Sections
The first OpenCms JSP tag that we will examine is the template tag.
Our original template simply printed the title, generated a rudimentary navigation menu, and included the body of the requested page. This worked fine for our examples, but we can make the template much more versatile with a few extensions. Doing this can make it useful for other JSP pages, as well as for advanced pages.
We want to break the template into pieces that can be identified and selectively used. In our first example, there was no way to address a particular part of the template. JSP pages that use a template need to be able to identify where the top (head) of the template should go and where the bottom (foot) should go. Here is our previous example partitioned into a header, body, and footer.
<%@ page session="false" %> <%@ taglib prefix="cms" uri="http://www.opencms.org/taglib/cms" %> <cms:template element="head"> <!DOCTYPE html public "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title><cms:property name="Title" escapeHtml="true"/></title> <link type="text/css" rel="stylesheet" href="<cms:link>/system/modules/tv.alephnull.modules.templates/resources/main.css</cms:link>"/> <cms:editable/> </head> <body> <h1><cms:property name="Title" escapeHtml="true"/></h1> <div name="menu" style="float:left;border:1px solid gray;padding: 3px;"> <b>Menu</b><br /> <cms:include file="../elements/navigation.jsp"/> </div> </cms:template> <cms:template element="body"> <cms:include element="text1" editable="true"/> </cms:template> <cms:template element="foot"> </body> </html> </cms:template>
As you can see, there are three template sections called head, body, and foot. Each of these sections can be called by name from an OpenCms include tag.
When processing page files, OpenCms reads through the template file in order, applying each template as it is encountered. (This means that, if you defined the foot before defining head, the foot would be printed before the head.)
None of the sections is added by default to a document of any other type besides Page. In a moment, we will look at the process of creating a JSP document that uses a template. In the process, we will see how this breaking up of the template can come in useful.
Finally, there is no hard and fast rule about template sections. While it is a good idea to call them head, body, and foot and some other OpenCms applications might assume their existence, you can add others if you wish.
For instance, I could define a template element called hello that contained a short message.
<cms:template element="hello"> <p> <b>Hello!</b> </p> </cms:template>
While it would show up by default in any pages, it would be accessible to other JSP files with a separate include. This mechanism allows you to conditionally apply template elements in JSP pages that are automatically applied to page documents.
[edit] Using Templates from a JSP Document
Just as we can create page documents in the OpenCms file system, we can also create JSP documents in the file system. JSP documents can be useful for handling forms or displaying dynamic information. But using templates with JSP pages is different from using templates with page files.
Now that our JSP template is complete, we can create a JSP document that uses it. We will create a JSP document called /playground/cms-info.jsp. Click the New button to create a new file, and choose JSP from the list of types. There is only one default parameter to set for a JSP file, Name, and we will set this to cms-info.jsp.
When we created the JSP template, we looked at the properties for a JSP page. While the Title property is useful (and will be used by the template), everything else can remain as the default specifies. But we are not ready to click Finish. We will need to use the Advanced button to edit one additional property for the JSP file. We will need to set the template that the JSP will use.
Near the bottom of the Individual Properties list in the Advanced Properties page, there is a field labeled template. We need to set this to point to our new template: /system/ modules/tv.alephnull.modules.templates/templates/example_template.
You can also access the Advanced Properties page for a file by clicking on the file's icon in the explorer view, choosing Properties, and clicking the Advanced button in the lower-right corner.
Click Finish to save the new file, and then open the file for editing.
We want to create a very simple JSP page that uses our template. We will start by creating the basic framework for the page:
<%@ page session="false" %> <%@ taglib prefix="cms" uri="http://www.opencms.org/taglib/cms" %> <cms:include property="template" element="head"/> <p>This is a JSP page.</p> <cms:include property="template" element="foot"/>
The page begins with the typical JSP declarations in which we import the cms taglib.
We have already assigned a template to this document, and we have broken the template into three sections. Now, we can selectively access the elements in that template.
The OpenCms include tags import the head and foot elements from the template. When this page is processed, these tags will be replaced by the contents of the head and foot elements.
Since we are not accessing the body of a particular Page file, there is no need to import the body element from the template. Instead, I just added a paragraph of text:
<p>This is a JSP page.</p>
When the above JSP is requested by the client, it will produce a page that looks like this:
We have seen how to create a JSP page and assign a JSP template to the page. Now, we will continue on and look at some other features of the OpenCms JSP tag library.
[edit] The property Tag
The JSP tag library provides some handy tools for providing information about resources within OpenCms. For instance, it is often useful to be able to get information about a particular file.
The OpenCms tag library's property tag gives us access to any of the properties associated with the file. For example, we can access the template property that we just set. To do this, we can simply add the following line above the final include in the JSP we created above:
This file uses the template <cms:property name="template"/>
The property element will be replaced with the value of the template property in this case, the absolute path in the VFS to the template: /system/modules/ tv.alephnull.modules.templates/templates/example_template.
In fact, we are not strictly limited to the file at hand. Here's how we could grab the Title property from the index.html file in the same folder:
<p>The index.html file has the title <b><cms:property file="index.html" name="Title"/></b> </p>
In short, you can use the property tag to get the values of properties for files in the VFS.
[edit] The link Tag
Since we are referring to the index.html file anyway, we might as well provide a link to it. Linking within OpenCms could be very confusing. To write a link, you would have to know where the resource is in the VFS, whether the resource is served statically or dynamically, how Tomcat is configured, etc. Fortunately, you won't have to worry about these things. The OpenCms tag library provides a tag that handles this for you the link tag.
The link tag is simple. It has no attributes and contains only the path to the file it will expand. For example:
<cms:link>index.html</cms:link>
This line of code generates the full path of the index.html file.
The above example works because the index.html file is in the same directory as our JSP. But if the file is in a different location in the VFS, then you will need to use the full VFS path, like /sites/default/playground/index.html. For an example of this, take another look at the JSP template we created at the beginning of this tutorial.
To create a link to another file in OpenCms, you will need to create a hyperlink that looks something like this:
<p> Go to <a href="<cms:link>index.html</cms:link>"> <cms:property file="index.html" name="Title"/></a> </p>
When the server processes these directives, it will send the client a piece of HTML that looks like this:
<p> Go to <a href="/opencms/opencms/playground/index.html"> My Playground</a> </p>
The URL in the href attribute now has an absolute path to the index.html file, and the OpenCms property tag has been replaced with the full title of the file.
[edit] The user Tag
Another useful tag in the OpenCms tag library is the user tag. We looked at this tag briefly before, but now we will examine it in a little more detail.
The user tag provides access to information about the current user.
<h2>User Info</h2> <p>The current user is <cms:user property="name"/>.</p> <p>The current group is <cms:user property="group"/>.</p>
The name property will be replaced by the full name of the user, while the group property will be replaced by the user's current group.
The property attribute determines which user information will be returned instead of the user tag. The available properties are name, group (or currentgroup), defaultgroup, firstname, lastname, email, street, zip, city, description, and otherstuff. The otherstuff attribute is not particularly useful. It is actually an unformatted dump of the contents of the java.util.Hashtable that stores extra user information.
[edit] The info Tag
The next tag in the OpenCms tag library that we will cover is the info tag, which returns information about OpenCms, the Java VM, and the underlying operating system. Syntactically, it is almost identical to the user tag. Here is an example that prints out the vital information about the platform:
<h2>System Info:</h2> <p>The requested URL is <b><cms:info property="opencms.url"/></b></p> <p>Currently, you are running OpenCms <cms:info property="opencms.version"/> with the <cms:info property="java.vm.vendor"/> <cms:info property="java.vm.name"/> version <cms:info property="java.vm.version"/> on <cms:info property="os.name"/>, <cms:info property="os.version"/> (<cms:info property="os.arch"/>).</p>
When this JSP is run, the client will see something like this:
In addition to information about the platform, the info tag provides a wealth of information about paths and URIs and can be very useful for constructing links when the OpenCms link tag will not do.
[edit] The img Tag
The img tag is new in OpenCms 6.2. It provides the functionality of the HTML img tag, plus automatic path adjustment for the VFS (like the OpenCms link tag) and server-side image scaling. The image scaling feature can be very useful. You can reference full-sized images in the VFS and use the img tag to generate thumbnails. The code for the OpenCms img tag looks the same as the HTML img tag:
<cms:img src="/playground/my_images/funny_head.jpg" alt="Funny Head" height="130" width="120" />
The value of the src attribute is the image's location in the VFS. OpenCms automatically re-writes this into the appropriate URL.
The height and width attributes specify the dimensions of the image. OpenCms uses this information to scale the image. In the example above, the original image is 200 180. OpenCms will scale the image down to 130 120 before sending it to the client's web browser.
If the dimensions do not maintain the same aspect ratio as the original image, then the background of the image will be padded the image will not be stretched. That means you don't have to worry about distorting the image when scaling it.
The attributes of the regular HTML img tag, like alt, style, and border, are also supported by the OpenCms img tag. Here's a piece of code that contains both the OpenCms img tag and the regular HTML img tag:
<img src="<cms:link>/playground/my_images/funny_head.jpg</cms:link>" alt="Funny Head" /> <cms:img src="/playground/my_images/funny_head.jpg" alt="Funny Head" height="130" width="120" scaleType="stretch" />
When this code is run, the output looks like this:
The image on the left is the one using the HTML img tag. OpenCms has scaled the one on the right.
Here is the URL that OpenCms generates: http://localhost:8080/opencms/ opencms/playground/my_images/funny_head.jpg?__scale=w:120,h:130. You may notice that the scaling information is appended to the end. For images stored in the VFS, you can directly instruct OpenCms to scale images by providing this information at the end of a URL.
[edit] The decorate Tag
Another tag introduced in OpenCms 6.2 is the decorate tag. This tag can be used to take an existing piece of HTML and automatically add new formatting according to a pre‑defined pattern.
For example, we could set up a decorate tag that would find all instances of "VFS" and surround them with the HTML abbreviation tag, abbr. This would take the text:
In OpenCms, all files are stored in the VFS.
and turn it into:
In OpenCms, all files are stored in the <abbr title="Virtual File System">VFS</abbr>.
Since the decorate tag can be inserted into templates, it can be used to automatically decorate the contents of page files authored in the WYSIWYG editor.
Using the decorate tag is a little more complicated than other tags because the it uses a configuration file and one or more text files to figure out what to decorate and how to decorate it, so the first thing we will need to do is create the configuration files.
[edit] Decorator Configuration Files
There are two types of configuration files. First, there are CSV (Comma Separated Values) files that contain lists of the terms to be decorated. Also, there is an XML configuration file that contains information on how to decorate the terms in the CSV file.
The configuration information is stored in a shared folder: /system/shared/decoration. (Note that you will have to be able to access the /system folder.) We will create our CSV file in this folder.
To do this, create a text file in /system/shared/decoration called decorationAbbr.csv. This file will contain the fields that tell the decorator what to look for and what information needs to be added.
VFS|Virtual File System CSV|Comma Separated Values CMS|Content Management System WYSIWYG|What You See Is What You Get
Note that the field delimiter above is not a comma (as the name CSV would suggest) but a vertical pipe ( |').
The first entry is the pattern that the decorator will look for. The second entry is the information that the decorator will need to decorate the text in this case, the term that will be put in the title attribute of the abbr tag.
In addition to the default decoration file, you can create decoration files for specific locales. For example, we could create a file named decorationAbbr_de.csv that contains decoration data for German-language locales. OpenCms allows multiple locales to be set using different files.
Once the decorationAbbr.csv file has been saved, we can work on the XML configuration file. OpenCms comes with a generic decoration XML configuration file, which is stored in /system/shared/decoration/configuration.xml. Rather than modify this file, we will make a copy of the file and edit that copy.
To copy the file, click on the configuration.xml file icon, choose Copy, and name the copy my_decorations.xml. Click on the file icon for my_decorations.xml and choose Edit from the menu. This will open the XML editor.
If you are going to set up multiple locales, check the Locale depending decoration checkbox. If this is checked, OpencCms will automatically search for locale-specific CSV files for this decoration. Next, click the target button on the right. This will bring up a context menu with a button shaped like a green plus sign. Click this button to add a new decoration definition.
Now, seven new fields are available. The first field, Name, is for giving this decorator a human-readable name.
The Mark first occurance checkbox, if checked, instructs OpenCms to treat the first occurrence of a match differently from subsequent versions of a match. In our case, we are adding abbr elements. For the first occurrence, we want the value of the title attribute to be "Virtual File System", but for subsequent occurrences, we don't want to assign the value to the title attribute at all, so in this case, the box should be checked.
The next two fields, Pre‑Text and Post‑Text, specify what should come before and after each match. For our example, Pre‑Text is <abbr> and Post‑Text is </abbr>. However, we want the first occurrence of each term to be marked with the title. The next two fields, Pre‑Text (first occurance) and Post‑Text (first occurance), are for specifying pre- and post-text for the first occurrence only.
For the first occurrence of any abbreviation, we want the title attribute to be filled using the second element in the CSV file created above. For VFS, the decorator should search the CSV file and find VFS|Virtual File System. We want that second field to be placed in the title attribute. So the field Pre‑Text (first occurance) should be given the value, <abbr title="{$decoration}">. {$decoration} will be replaced by the second field in the CSV file.
There is a second variable, aside from {$decoration}, that is available the {$locale} variable, which will contain the name of the locale currently used.
The final field, Decoration File, should contain the full path reference of the CSV file that holds the definitions.
Once everything is complete, click the "save and close" button (the yellow floppy disk with a black X) to save the definition and exit the XML editor. We are now ready to test the decorator.
[edit] Using the decorate Tag
Going back to our JSP page in the /playground folder, we can now add a decorator section:
<cms:decorate file="/system/shared/decoration/my_decorations.xml"> <p> OpenCms is a CMS that uses the VFS to store files, and a WYSIWYG editor to create and modify content. </p> </cms:decorate>
The decorator will search through all of the text between the decorate tags and surround any matching terms with abbr tags.
The decorate tag has two attributes, file and locale. The file attribute tells the decorator where the XML configuration file is. The optional locale attribute lets you explicitly set which locale should be used.
The result of our JSP in action looks like this:
Note that the terms we specified in the CSV file, "CMS", "VFS" and "WYSIWYG", have a dotted underline. Hovering the mouse pointer over one of these terms (as I did above over the term CMS) displays a context box that shows what the abbreviation stands for ("Content Management System").
As I mentioned before, you can use the OpenCms decorate tag in a template file. That way, the contents of a page file are run through the decorator. But there is one caveat when doing this you will need to turn off caching for the import tag. For example, applying a decorator to the body of a template would look like this:
<cms:template element="body"> <cms:decorate file="/system/shared/decoration/my_decorations.xml"> <cms:include element="text1" editable="true" cacheable="false"/> </cms:decorate> </cms:template>
This is from the body section of the template. The decorate tag is the same as in the previous example, but to make sure the decorator works, we need to set the include tag's cacheable attribute to "false".
That is all there is to using the decorate tag. Of course, the examples I've given above are fairly straightforward. The decorator is an advanced tool, and with a little creativity, you can use it to accomplish more complex processing.
At this point, we have walked through the basics of the OpenCms taglib. OpenCms includes additional documentation on tag libraries in the OpenCms JSP Taglib Documentation Alkacon documentation module.
[edit] Documentation and TemplateOne
Now that we have walked through the process of creating a simple module, you may want to move on to more sophisticated creations. OpenCms includes plenty of documentation to help you on your way. You may want to look at the OpenCms TemplateOne templates, which provide a sophisticated pre-built template environment (built with tag libraries, scriptlets, and Java objects). OpenCms includes built-in documentation on the TemplateOne templates.
At this point, we have covered the basics of template creation. The remainder of this tutorial will explain how to avoid some of the common pitfalls of OpenCms template development.
[edit] A Few Things to Watch Out For
Whether using a tag library or writing scriptlets, there are a few things that can cause confusion and surprise to developers new to the platform.
[edit] The File System
The VFS, in spite of its name, does not behave exactly like a real file system. Furthermore, neither the servlet engine nor the JSP interpreter is aware of the existence of the VFS. When using JSP tags, be wary of the JSP include and directive tags, and the import tag from the Java Standard Tag Libraries (JSTL). These tags do not handle the VFS/real file system split very well and can have some unpredictable results. According to OpenCms developers, judicious use of the import tag will work for some files, but the caveats are many, so I do not recommend it. The best way to handle inclusions is to use the OpenCms tag library's include tag (as we have done already), or its API equivalent, the CmsJspActionElement class's include method.
The built-in Java IO classes are also not aware of the VFS, and it is not possible, for example, to open a FileReader object on a location inside of OpenCms. There should be no need for this, as the CmsObject class provides methods for VFS file access.
[edit] Redirecting and Forwarding
OpenCms provides a custom subclass of HttpServlet, and some of the behaviors of this subclass do not match what the JSP interpreter assumes. This is the case with forwarding (using the JSP forward tag), which simply does not work in OpenCms. In the OpenCms documentation, the recommendation is that developers attempt to use the tag library provided for handling the problem. However, redirecting is straightforward and can be done in a scriptlet by executing the response object's sendRedirect method.
[edit] Dynamic Content and Publishing
Development is usually done by a user who has administration privileges, and tests are often performed (as we've done so far) on the Offline project. However, security settings for a visitor to the site are markedly different from those for an internal administrator, and code that works during development may fail for security reasons when a visitor tries to execute it. Likewise, publishing files from the Offline project to the Online project can change expected behavior if some or all of the content is exported. When JSP pages are exported statically (not the default behavior), they will be rendered once into static HTML, and will lose all of their dynamic functionality. Likewise, hard-coded links that do not use the OpenCms tag library's link tag can break or point to non-existent documents.
Obviously, the solution to this problem is to be aware of the problem and test a lot. If you are doing static exports of content, make sure you test out the template code. When content is rendered as static HTML, the JSP template is also rendered once. In my early exposure to OpenCms, I discovered this when I used the java.util package's Date class in my main template. Two days after publishing my files as static resources, I realized with horror (or acute embarrassment) that the date hadn't changed since I published the project. Setting the export property to false for JSP files should keep this from happening.
[edit] Structuring Code and Content
OpenCms is designed to be flexible, allowing organizations to adapt it to their own needs. Because of this, JSP files can get scattered around the VFS, and valuable (and reusable) functionality can be lost in a labyrinth of content folders. A well designed development process, though, should not allow this to happen.
The OpenCms module structure provides an ideal mechanism for structuring code in a way that promotes reuse and organization. That is why we created a module before writing the first JSP. By structuring things wisely from the beginning, we avoid a JSP diaspora.
As a general rule, move as much JSP code as possible into a module, particularly code that performs useful functions. If you find that a large number of scripts have a functional similarity (e.g. a set of blogging scripts), you may decide to create a new module specifically for that set of tasks.
As an added advantage, modules are designed to be versioned and moved, and they can vastly improve the development-to-production process. The site can be designed and developed in a module on a development server and then exported. Then it can be imported into the testing and production environments. Since content exists separately (outside of the module), there is no risk of losing valuable content or migrating development content into production. The built-in versioning makes it very easy to quickly ascertain the state of each server.
[edit] Additional References
For instructions on Installing OpenCms, click here
[edit] Source
The source of this content is Chapter 6:Customizing the Site of Building Websites with OpenCms by Matt Butcher (Packt Publishing, 2007).