magnoliacms technical guide

108
Magnolia CMS Technical Guide Authors: Antti Hietala , Philipp Bärfuss Date: 27.07.2010 Version: 1.0 Copyright Magnolia International Ltd. 2010. All rights reserved. No part of this document may be reproduced in any form without prior permission in writing from Magnolia International Ltd. Magnolia International Ltd. 1

Upload: csarpm

Post on 21-Nov-2015

144 views

Category:

Documents


3 download

DESCRIPTION

MagnoliaCMS Technical Guide

TRANSCRIPT

  • Magnolia CMS Technical Guide

    Authors: Antti Hietala, Philipp BrfussDate: 27.07.2010Version: 1.0

    Copyright Magnolia International Ltd. 2010.All rights reserved. No part of this document may be reproduced in any form without prior permission in writingfrom Magnolia International Ltd.

    Magnolia International Ltd.

    1

  • Table of contentsIntroduction to Magnolia CMS architecture............................................................................................ 6AdminCentral............................................................................................................................................. 7Authoring................................................................................................................................................... 9Instances ................................................................................................................................................. 12

    Public instances serving different content ............................................................................................. 13Intranet and extranet ............................................................................................................................. 14Planned redundancy and high availability ............................................................................................. 14Instance configuration examples........................................................................................................... 15

    Content delivery ...................................................................................................................................... 16Subscribers............................................................................................................................................ 16

    Content storage and structure............................................................................................................... 17Repository ............................................................................................................................................. 17Workspaces........................................................................................................................................... 17

    Magnolia CMS workspaces ............................................................................................................... 19Hierarchical content store...................................................................................................................... 20JCR standard API for content repositories ............................................................................................ 21Persistent storage ................................................................................................................................. 22

    Clustering ................................................................................................................................................ 24Jackrabbit clustering.............................................................................................................................. 24

    Modules.................................................................................................................................................... 26Pluggable and independent................................................................................................................... 26Configuration ......................................................................................................................................... 27JAR structure......................................................................................................................................... 28Module class ......................................................................................................................................... 29Dependencies ....................................................................................................................................... 29Module life-cycle.................................................................................................................................... 30Bootstrap files........................................................................................................................................ 30Version handling.................................................................................................................................... 31Community driven module development ............................................................................................... 32

    Magnolia webapp .................................................................................................................................... 33Directory structure ................................................................................................................................. 33Adding the Magnolia main filter to the webapp ..................................................................................... 34Adding the Magnolia context listener .................................................................................................... 35

    Request processing and filters.............................................................................................................. 36Magnolia CMS filter chain ..................................................................................................................... 36

    Magnolia International Ltd.

    2

  • Templating............................................................................................................................................... 39Pages and paragraphs .......................................................................................................................... 39Templating mechanism ......................................................................................................................... 40Component relations ............................................................................................................................. 41Templating languages ........................................................................................................................... 42Tag library.............................................................................................................................................. 43Example of CMS tags in use ................................................................................................................. 45Templating support objects ................................................................................................................... 46

    Dialogs ..................................................................................................................................................... 47Tabs and controls .................................................................................................................................. 47Dialog configuration............................................................................................................................... 48

    Create a dialog definition ................................................................................................................... 49Map the dialog to a paragraph........................................................................................................... 50Add the paragraph on a page ............................................................................................................ 50

    Best-practice Standard Templating Kit................................................................................................. 51Contents ................................................................................................................................................ 51Benefits ................................................................................................................................................. 51STK components ................................................................................................................................... 52Site definition ......................................................................................................................................... 52Areas ..................................................................................................................................................... 54Template inclusion ................................................................................................................................ 56Customization........................................................................................................................................ 57

    Template prototype............................................................................................................................ 58Static HTML prototype ....................................................................................................................... 61

    Design with CSS ................................................................................................................................... 64Layout and grid...................................................................................................................................... 64

    HTML structure .................................................................................................................................. 66Body IDs and classes............................................................................................................................ 67

    CSS configuration .............................................................................................................................. 67Learn more ............................................................................................................................................ 69

    Rendering engine.................................................................................................................................... 70Steps involved in rendering content ...................................................................................................... 71Renderers.............................................................................................................................................. 72Rendering order .................................................................................................................................... 72

    Magnolia CMS API................................................................................................................................... 73Magnolia Context / Aggregation State................................................................................................... 73Content API ........................................................................................................................................... 74Components and modules .................................................................................................................... 74Templating............................................................................................................................................. 74

    Magnolia International Ltd.

    3

  • Configuration mechanisms.................................................................................................................... 76Properties .............................................................................................................................................. 76Multiple configurations in the same Web application archive (WAR) .................................................... 77Components .......................................................................................................................................... 77Content2Bean ....................................................................................................................................... 78

    Where is Content2Bean used?.......................................................................................................... 79Extending configuration ..................................................................................................................... 80

    Observation ........................................................................................................................................... 80Integration options.................................................................................................................................. 81

    Custom filter. ......................................................................................................................................... 81Custom servlet....................................................................................................................................... 82Forwarding a request ............................................................................................................................ 83Custom renderer ................................................................................................................................... 83Spring (Blossom) module ...................................................................................................................... 83Direct calls to rendering engine............................................................................................................. 84Web services, AJAX and snippets ........................................................................................................ 84Reading content directly ........................................................................................................................ 84

    Internationalization and localization ..................................................................................................... 85System................................................................................................................................................... 85

    Dialogs............................................................................................................................................... 86Template scripts................................................................................................................................. 87

    Content .................................................................................................................................................. 87One hierarchy or many ...................................................................................................................... 88Storing localized content.................................................................................................................... 88Delivering localized content ............................................................................................................... 89

    Authoring ............................................................................................................................................... 90Unicode ................................................................................................................................................. 92

    Security .................................................................................................................................................... 93Users ..................................................................................................................................................... 93Groups................................................................................................................................................... 94Roles ..................................................................................................................................................... 94ACLs...................................................................................................................................................... 94Custom login forms................................................................................................................................ 96

    Data module............................................................................................................................................. 97Types..................................................................................................................................................... 98Dialogs................................................................................................................................................... 99Content ................................................................................................................................................ 100

    Magnolia International Ltd.

    4

  • Cache ..................................................................................................................................................... 101Cache filter .......................................................................................................................................... 101Policy configuration ............................................................................................................................. 101Caching while developing.................................................................................................................... 102How caching works ............................................................................................................................. 102Ehcache back end............................................................................................................................... 103Advanced cache strategies ................................................................................................................. 103

    Workflow................................................................................................................................................ 104Engine ................................................................................................................................................. 105Participants.......................................................................................................................................... 105Workitems in inbox .............................................................................................................................. 106Integration with external processes..................................................................................................... 106

    Resources.............................................................................................................................................. 108

    Magnolia International Ltd.

    5

  • 1. Introduction to Magnolia CMS architecture

    Magnolia CMS is an open-source Web Content Management System that focuses on providing an intuitive userexperience in an enterprise-scale system. Its combination of ease-of-use and a flexible, standards-based Javaarchitecture has attracted enterprise customers such as ING, JBoss.org, Johnson & Johnson, Lloyds TSB, Sony,Seat, Unilever and The US Department of Defense. Magnolia CMS is used by governments and Fortune 500enterprises, and in more than 100 countries.Architectural features that make Magnolia CMS suitable for versatile enterprise use are:

    Java platform. Magnolia CMS is built on top of the Java Enterprise Edition platform. Java EE reducesthe cost and complexity of developing multi-tier enterprise services. Java EE applications can be rapidlydeployed and easily enhanced as the enterprise responds to competitive pressures. Java providesfurther benefits to enterprises such as standardization, availability of trained talent, and a solidmarketplace for competing offers to drive innovation. Magnolia CMS is implemented as a Java EE webapplication. A typical web application consists of modules that can be other web applications, EnterpriseJavaBeans (EJB) or application clients. In Magnolia CMS, nearly everything is a module. Even theAdminCentral, a content editor's view into the CMS, is a module. A Java EE application is a set ofmodules with some added glue that binds them together into a complete integrated application.

    JCR standard. JCR stands for Content Repository API for Java. It is a specification for a Java platformAPI for accessing content repositories in a uniform manner. Repositories are used to store the contentdata and related meta data such as versioning information.

    Clustering by having multiple public instances. Magnolia CMS is distributed as two web-applications,one acting as the authoring instance and the other as the public environment. This has several benefits.It allows for better security by having one application inside your firewall and one outside. You canincrease the number of public instances to guarantee high availability. Separate public instances canserve geographically targeted content or multiple languages.

    Magnolia International Ltd.

    6

  • 2. AdminCentral

    AdminCentral is a Magnolia CMS user interface for performing site management and configuration tasks. This iswhere administrators and editors work. AdminCentral provides a navigation menu for common tasks on the leftand displays web pages and configuration on the right.

    Some of the key menu items are: Website. Here you create and manage web sites. A site hierarchy is displayed as a tree that consists of

    pages. Documents. Built-in document management system (DMS) for storing documents, images and other

    binary resources that you want to use on the web pages. Full-text indexed and searchable. Forums. Built-in discussion forums for use on a website. You can manage user permissions with

    Magnolia CMS's built-in security module. Inbox. Incoming messages such as workflow notifications. Data. Create and manage custom data types such as contacts, client references and customer cases.

    You could for example create a custom data type "Client", populate it with recently won clients, andshowcase them on your website. Here you can also aggregate RSS feeds from external sources.

    Templating Kit. Best-practice templating framework that speeds up site creation and reduces projectrisk. Ships with common use case examples such as articles, news, forms, public user registration andmore, yet allows you to create completely custom sites. See Templating Kit below for more.

    Magnolia International Ltd.

    7

  • Security. Manage users, groups, roles and permissions. Public user registration is also managed here. Configuration. Everything in Magnolia CMS can be configured via AdminCentral: cache, menus,

    dialogs, workflows, modules...all of it. Tools. Maintenance tools for logging, importing and exporting, querying, mail and backup. Packager. A special tool to help with site migration. You can package an entire website or part of it and

    move it to a different Magnolia CMS instance. Magnolia Store. Store for downloading custom modules that extend Magnolia CMS.

    Magnolia International Ltd.

    8

  • 3. Authoring

    Authoring is the process of writing web content and managing it as part of the website. This includes allowingnon-technical users to contribute content in an easy and intuitive manner.Content is authored in the browser. The user interface for content authors supports in-place editing. This is amode of working where the edited page looks and behaves just like the live page. New paragraphs are displayednext to existing paragraphs in accurate context. Authors can immediately see what effect adding a new piece ofcontent has on the page and move the content around if needed.When you double-click a page in the site tree in AdminCentral, the page is opened for editing.

    Magnolia International Ltd.

    9

  • Each page is made up of pre-defined content areas that can be controlled with templates. Editable content itemswithin these areas are called paragraphs. Paragraph is the smallest block of content that end users can edit,delete and move as a unit. Think of paragraph as content that "belongs together". At its simplest, a paragraphconsists of a heading and some text. However, it can contain almost anything: a related image, links to otherarticles in the same category, teased content from a sub page and much more. Editable paragraphs are identifiedwith green toolbars.

    Magnolia International Ltd.

    10

  • Clicking the Edit button in the green toolbar opens a dialog. A dialog is an HTML form with fields for editingparagraph content and metadata. The data you enter into the fields is stored in the repository and ultimatelyrendered as a paragraph on the page.

    Magnolia International Ltd.

    11

  • 4. Instances

    Magnolia CMS is distributed as two web-applications, one acting as the authoring instance and the other as thepublic environment. This allows for better security, having one application inside your firewall and one outside. Italso enables clustering configurations.

    Author instance is where all authors work. It typically resides in a secure location such as behind a corporatefirewall, inaccessible from the Internet. The author instance publishes content to public instances.Public instance receives the public content and exposes it to visitors on the Web. It resides in a public, reachablelocation. You can have more than one public instances, serving the same or different content.Each instance functions as an independent application but technically they are the same. An author instance canbe configured to function as a public instance and vice versa. The differences are small adaptations inconfiguration and security. Security for the public instances is usually managed separately.

    Magnolia International Ltd.

    12

  • 4.1. Public instances serving different content

    You can manage multiple sites from the same author instance. Each public instance can serve content targetedfor a specific geographical area, for example.

    Magnolia CMS's multi-site feature provides granularity for content control on multi-language and multi-domain installations. Administrators have the option to direct content authors to the public site through a specificdomain. Authors edit only the part of the content structure that resides at the specified domain. To ensure aconsistent browsing experience, URLs are adapted to always reflect the domain. You can also configure multipledomains to access the same instance.

    Magnolia International Ltd.

    13

  • 4.2. Intranet and extranet

    Magnolia CMS allows for flexibility in placing secure and sensitive application instances. The diagram belowillustrates a possible placement strategy where an extranet publishing instance resides outside the firewall but anintranet instance is inside. More advanced configurations can be built to place intranet and extranet instancesinside a firewall, for example.

    4.3. Planned redundancy and high availability

    A distributed instance setup allows you to responding to high availability requirements and sudden increases intraffic. Each of the following problem scenarios can be addressed by adding a new public instance to serve thesame content, helping existing instances deal with the load.

    Public instance failure. Imagine you have two public Magnolia CMS instances and due to hardwarefailure one of them is out of operation for a few days. Start a new public instance to replace the brokenone.

    Sudden high load on your site, also known as Slashdot effect. Spin off new public instances until thetraffic subsides.

    Public instance blackout. All public instances are corrupted, broken or compromised. No instances existto serve content.

    Magnolia International Ltd.

    14

  • 4.4. Instance configuration examples

    Magnolia CMS configurations range from a minimal one-machine setup to a standard three-instance productionsetup and beyond.

    Minimal. Author and Public instances exist on the same server. This is the default configuration whenyou install Magnolia CMS on your computer to try it.

    Reduced. Author and Public instances exist on separate servers. The two Public instances are on thesame server or one of the Public instances resides on the same server as the Author instance.

    Standard. Public instances exist on separate servers. This configuration enables load balancing.Incoming requests can be directed to one server or another depending on availability.

    Magnolia International Ltd.

    15

  • 5. Content delivery

    Content is published from the author instance to the public instances via activation. Content authors create newcontent on the author instance and then activate it. Activation can trigger an optional editorial workflow in whichan editor reviews the changes and approves them for publication. On approval, the new content is transmitted tothe public instance.

    5.1. Subscribers

    Public instances that receive the activated content are known as subscribers. Any number of subscribers cansubscribe to a single author instance. Subscribers are key to building high-availability, load-balancedenvironments since they can be configured to receive targeted content. A subscriber configuration defines theaddress of the subscriber and the type of content it should receive.Example: The image below shows the configuration for subscriber "nbasuperstars-com". The subscriber residesat URL http://www.nbasuperstars.com:8080/magnoliaPublic. This is the location of the publicinstance on the Internet. The subscriber is active which means it will receive content when activation isexecuted. Not all content is published to this subscriber, however. It subscribes only to content residing atpath /sports on the author instance. This is an example of mapping a public instance to a subsection of thecontent hierarchy.

    Subscribers can subscribe to any content item: websites, subsections of websites, configuration settings, customdata types and data nodes, forums, comments, documents, images and so on.

    Magnolia International Ltd.

    16

  • 6. Content storage and structure

    Magnolia CMS stores all content (web pages, images, documents, configuration, data) in a content repository.The repository implementation we have chosen, Apache Jackrabbit, adheres to the Java Content Repositorystandard (JCR).

    6.1. Repository

    A content repository is a high-level information management system that is a superset of traditional datarepositories. It implements content services such as:

    Granular content access and access control Hierarchical, structured and unstructured content Node types, property types (text, number, date, binary) Queries (XPath, SQL) Import and export Referential integrity Versioning Observation Locking Clustering Multiple persistence models

    A content repository can store text and binary data (images, documents). You don't need to worry about how thedata is stored. The repository provides a standardized way to store and retrieve it whether it resides in atraditional database or in a file system.

    6.2. Workspaces

    Magnolia CMS has one repository, magnolia, which in turn contains several workspaces. There is a workspacefor storing website content, another for user accounts, third for configuration and so on.Each workspace contains a single rooted tree of items. An item is either a node or a property. Each node mayhave child nodes and child properties. Properties cannot have children; they are the leaves of the tree. All of theactual content in the repository is stored within the values of the properties.

    Magnolia International Ltd.

    17

  • Here's what the object hierarchy in a repository looks like:1. Repository contains workspaces2. Workspace contains nodes3. Each workspace has a single root node.4. Node contains properties5. Properties store values (data)

    The changes you make to nodes and properties are transient in the workspace. Only when the system performs aworkspace save operation are the changes persisted into permanent storage such as a database.

    Magnolia International Ltd.

    18

  • 6.2.1. Magnolia CMS workspaces

    In its default configuration Magnolia CMS has the following workspaces: website. Websites, pages and paragraphs. This is where most of your site content is stored. config. Configuration settings for everything. data. Custom data types and data items. dms. Documents and images, typically binary data. templates. Page and paragraph templates in the Standard Templating Kit (STK) resources. JavaScript and CSS style sheet files used by the STK and themes. userroles. Roles and access control lists (ACL) for granting permissions to users. usergroups. Groups of users. users. System, administrative and public user accounts. and a few others...

    Magnolia International Ltd.

    19

  • Workspaces are mapped to repositories in WEB-INF/config/default/repositories.xml.

    ...

    The ability to map a workspace to a named repository provides interesting possibilities. While Magnolia CMSkeeps all workspaces in one repository by default, you don't have to. You could map a workspace to a differentrepository in order to:

    Provide a workspace with its own persistence manager. You could store users in one database andwebsite content in another.

    Use a different persistence mechanism according to how often the data is requested and how quickly itneeds to be available. For example, it might make sense to store search indexes on a fast disk butarchived web content on a slower disk.

    Store shared content such as user-generated comments in a clustered storage. This allows variousMagnolia CMS instances to access the same comments. See Jackrabbit clustering for an illustratedexample.

    Integrate your system with an external repository. As long as the external repository adheres to the JCRstandard, Magnolia CMS can access content in it.

    6.3. Hierarchical content store

    A content repository is designed to store, search and retrieve hierarchical data. Data consists of a tree ofnodes with associated properties. Data is stored in the properties. They may store simple values such asnumbers and strings or binary data (images, documents) of arbitrary length. Nodes may optionally have one ormore types associated with them, which in turn dictates the type of their properties, the number and type of theirchild nodes, and certain behavioral characteristics.

    Magnolia International Ltd.

    20

  • Example: A, B, C and D are nodes. The boxes represent properties with Boolean, numerical, string and binaryvalues.

    6.4. JCR standard API for content repositories

    Java Content Repository (JCR) is a standard interface for accessing content repositories. JCR version 1.0 wasspecified in Java Specification Request 170 (JSR-170). Version 2.0 in JSR-283 is also final. JCR specifies ahierarchical content store with support for structured and unstructured content.Magnolia CMS was the first open-source content management system built specifically to leverage JCR. Thestandard decouples the responsibilities of content storage from content management and provides a common APIthat enables standardized content reuse across the enterprise and between applications. Magnolia CMS uses theopen-source Jackrabbit reference implementation.

    Magnolia International Ltd.

    21

  • Application developers benefit from standardization as they don't need to learn several vendor-specific APIs.Learning one standard API allows them to work with any compliant repository and write code againstit. Businesses enjoy the freedom of choice. Open standards like JCR are the best medicine against vendor lock-in; any CMS that supports the JCR standard becomes a viable alternative. Costs associated with switchingvendors are smaller when your content is already the correct format.

    6.5. Persistent storage

    A persistence manager (PM) is an internal Jackrabbit component that handles the persistent storage of contentnodes and properties. Each workspace of a Jackrabbit content repository can use a separate persistencemanager to store content for that workspace. The persistence manager sits at the bottom layer of the Jackrabbitsystem architecture. Reliability, integrity and performance of the PM are crucial to the overall stability andperformance of the repository.Important! In order to avoid integrity issues and to benefit from services such as observation, clustering andindexing, you should always access the content through the JCR API. Changing the data directly (bypassingthe API) causes serious issues. This may sound restrictive but the API is actually quite versatile. You can evenaccess the content repository from external applications using the API.

    Magnolia International Ltd.

    22

  • The choice of persistence managers includes: Database: Magnolia CMS uses a database as persistence manager by default. This is the most

    common option. We ship WAR files and operating system specific bundles with the Derby database.Derby is an embedded database that allows us to package a fully operational Magnolia CMS exampleinto a single download, including configuration details and demonstration websites. It requires minimalinstallation effort from users. However, for production environments we recommend an enterprise-scaledatabase such as MySQL, PostgreSQL, Oracle or MS SQL Server. All of them work with JCR. Databaseconnections are based on JDBC, involve zero deployment, and run fast.

    File system: This kind of data store is typically not meant to run in production environments, except inread-only cases, but it can be very fast.

    In-memory: This is a great persistence manager for testing and for small workspaces. All content is keptin memory and lost as soon as the repository is closed. Even faster than a file system. Again, not forproduction use.

    Magnolia CMS Enterprise Edition allows you to switch between persistence managers without losing any content.

    Magnolia International Ltd.

    23

  • 7. Clustering

    Magnolia CMS can be configured to run in a clustered environment to provide high availability and load balancing: High-availability clusters are also known as fail-over clusters. Their purpose is to ensure that content is

    served at all times. They operate by having redundant instances which are used to provide service whena public instance fails. The most common size for a high-availability cluster is two public instances, thestandard Magnolia CMS setup. In such a setup the redundant instance may even be dormant (notactively serving content) until it is called to service.

    Load-balancing clusters connect many instances together to share the workload. From a technicalstandpoint there are multiple instances but from the website visitor's perspective they function as a singlevirtual instance. A load balancer distributes requests from visitors to instances in the cluster. The result isa balanced computational workload among different instances, improving the performance of the site asa whole.

    7.1. Jackrabbit clustering

    We use Jackrabbit's clustering feature to share content between Magnolia CMS instances. Clustering inJackrabbit works on the principle that content is shared between all cluster nodes. This means that all Jackrabbitcluster nodes need access to the same persistent storage (persistence manager and data store). The persistencemanager must be clusterable. Any database is clusterable by its very nature as it stores content by unique hashIDs. However, each cluster node needs its own (private) file system and search index. For more details seeJackrabbit clustering documentation.As discussed in Workspaces, individual workspaces can be mapped to different repositories. The repository thatholds shared content can reside in clustered storage. This is useful for content that needs to be in sync across allinstances.

    Magnolia International Ltd.

    24

  • In the diagram below, each Magnolia CMS instance uses its own persistent storage (gray databases) for storingthe content of website, DMS and data workspaces. However, the comments workspace has shared content thatis stored in a clustered storage (blue database).

    User generated content such as comments written by site visitors is a typical clustering case. Imagine that usersJohn and Jane request the same web page. A load balancer redirects John to public instance A. When Johnleaves a comment on the page, his comment is stored in a workspace that resides in clustered storage. Now Janerequests the same page. The load balancer redirects her to public instance B. John's comment is immediatelyvisible to Jane since both instances tap into the same clustered storage.Other examples of shared content are user accounts, permissions of public users and forum posts. They need tobe available regardless of the instance that serves the page.

    Magnolia International Ltd.

    25

  • 8. Modules

    Magnolia CMS has a modular architecture. A module is a independent component that performs a particular taskor is used to package content and functionality. The system itself is built of modules; AdminCentral, DocumentManagement System and Workflow are all modules.You can use modules to:

    Create a custom component to address a specific requirement or use case. The Forum module is anexample of this. It provides forums where site visitors can participate in the discussion.

    Package an entire website for easy deployment, including customized templates, paragraphs andcontent.

    Package and deliver a set of assets such as images or documents.

    8.1. Pluggable and independent

    Modules are independent and pluggable in the sense that you can add and remove them at will. For example, ifyou don't need the Workflow module and would rather activate pages to the public instance directly, you canremove the module from Magnolia CMS.

    Magnolia International Ltd.

    26

  • A module consists of a set of components packaged in a JAR file. Deploying a module is a matter of copying theJAR file into the WEB-INF/lib folder and restarting the instance. Magnolia CMS update wizard recognizes theJAR and installs its contents.

    8.2. Configuration

    When you start Magnolia CMS, the system identifies available modules by locating each module's descriptor file.The descriptor is an XML file located in META-INF/magnolia inside the JAR. The name of the file is notimportant but we recommend that you follow a naming convention similar to moduleName.xml in your ownmodules, such as samples.xml.

    A minimal module descriptor looks like this:

    samples4.1.0

    Magnolia International Ltd.

    27

  • The descriptor is quite versatile. You can use it to register servlets and define workspaces too.After a module is installed it is listed under modules in the config workspace.

    Configured items are stored directly under the module node in order to be automatically registered by MagnoliaCMS. As the system monitors configured items, any changes in the configuration of registered items will be activeimmediately.

    8.3. JAR structure

    To use the special features of Magnolia CMS modules you need to follow some conventions and put additionalresources in well-defined places inside the module JAR. Here is a module source in Eclipse:

    It is common practice to define two source folders: src/main/java for Java classes and src/main/resources for module-specific resources. This structure is used in every Magnolia CMS module project. Here'swhat the folders should contain:

    Path ContentsMETA-INF If you have your own custom tab library put the tag library definition file (.tld) here.META-INF/magnolia Module descriptor file. Follow a naming convention like moduleName.xml.mgnl-bootstrap/moduleName

    XML files whose contents you want to be imported into the system when the moduleis installed.

    Magnolia International Ltd.

    28

  • mgnl-bootstrap-samples/moduleName

    XML samples whose contents you want to be imported into the system when themodule is installed. If property magnolia.bootstrap.samples is set to falsethese files are not imported.

    mgnl-files Files in this folder are copied to the web application folder. Folder hierarchy is alsocopied.

    mgnl-resources Static resources such as style sheets and JavaScript. They will be available at URI/.resources/.., for example /.resources/example/style.css.

    8.4. Module class

    The configuration node uses the Content2Bean mechanism to populate a JavaBean with the content of the confignode and its subnodes. Developers can access the module configuration through the Bean. You can define anoptional module class in your module descriptor if you need a more sophisticated implementation that can interactwith the module dynamically throughout its life-cycle.The module class is defined in the module descriptor:

    samples4.1.0info.magnolia.SamplesModuleinfo.magnolia.setup.SamplesVersionHandler

    Note that the Content2Bean mechanism is not limited to module configuration. It is used all over Magnolia CMS.

    8.5. Dependencies

    Modules can use functionality provided by the Magnolia CMS core code, the Standard Templating Kit and othermodules. When one module uses functionality from another this creates a dependency between modules.

    Magnolia International Ltd.

    29

  • You can define run time or install time dependencies but not build dependencies. If you define a dependency onanother module then the target module will be installed and started before your module. A dependency can beoptional which means that if an optional module is not present, installation will still proceed. If the optional moduleis present, it will be installed first.

    core3.6.0/*

    cache3.6.0/*true

    8.6. Module life-cycle

    Magnolia CMS monitors the module configuration and restarts a module if there are changes in the configuration.Be aware that this active monitoring applies to the entire module configuration, not only the config node.The system provides a simple way to logically associate module classes to the module life-cycle. If your moduleclass implements info.magnolia.module.ModuleLifecycle then you have to implement:

    public void start(ModuleLifecycleContext moduleLifecycleContext);public void stop(ModuleLifecycleContext moduleLifecycleContext);

    These methods are called whenever the module is started or stopped, which allows the inclusion of customprogrammed logic for individualized modules.

    8.7. Bootstrap files

    A module can provide configuration in a bootstrap file. The bootstrap file is a JCR export of configuration nodes.Storing the entire configuration for items such as dialogs in a bootstrap file has the advantage of easy re-purposing. You can share the XML with others and check it into version control.To export a configuration, right-click the parent node and select Export tree to XML. The export file format is JCRSystem View XML.The name of the exported XML file is adheres to convention workspace.path-to-configuration. Theexport function creates this name automatically. For example, exporting a configuration node at path /modules/dms/dialogs/dmsEdit in the config workspace will create an XML filenamed config.modules.dms.dialogs.dmsEdit.xml.

    You should place bootstrap files in the mgnl-bootstrap/moduleName directory inside your module JAR or inthe WEB-INF/bootstrap directory.

    Magnolia International Ltd.

    30

  • Bootstrap files are loaded in the same order as module dependencies, which allows them to override the defaultconfiguration. Files in WEB-INF/bootstrap are loaded last. If the target node already exists, it will be deletedand overwritten.Bootstrap files are installed only during module installation, not on updates. This guarantees that anycustomizations made to the configuration are not overwritten when the module is updated. This behavior can bechanged by providing a custom version handler.

    8.8. Version handling

    The module mechanism facilitates smoother Magnolia CMS version changes. The version handler registers thetasks to be executed during installation and tasks executed on updates.Version handler class is defined in the module descriptor:

    samples4.1.0info.magnolia.SamplesModuleinfo.magnolia.setup.SamplesVersionHandler

    If no version handler is defined, the system uses the default version handler which executes a basic set of taskssuch as register workspaces, register servlets and import bootstrap files.

    Magnolia International Ltd.

    31

  • 8.9. Community driven module development

    In addition to enterprise modules that ship with the Enterprise Edition, the open-source community contributesmodules for various purposes. You can find a list of available modules in the Magnolia Store. To access the storeclick Magnolia Store in AdminCentral or see the listing on the web.

    Magnolia International Ltd.

    32

  • 9. Magnolia webapp

    Java Web Application (webapp) is a collection of servlets, HTML pages, classes and other resources bundledtogether and run on a servlet container. The following items can exist in a webapp:

    Servlets JavaServer Pages Utility classes Static documents including XHTML and images Client side classes Meta information that describes the webapp

    9.1. Directory structure

    The directory structure is the container that holds the components of a webapp. The first step in creating aMagnolia CMS webapp is creating this structure. The following table describes what each directory shouldcontain.

    Path Contentscache/ Files with cached contentdocroot/ Files extracted from mgnl-files/docroot in

    the JAR.logs/ Magnolia log filesMETA-INF/ Meta information files, e.g. from Mavenrepositories/ Repositorytemplates/ Templates extracted from mgnl-files/

    templates in the JARtmp/ Temporary work directoryWEB-INF/ All resources related to the application that are

    not in the document root. WEB-INF directory isnot part of the public document. No filescontained in this directory can be served directlyto a client.

    WEB-INF/bootstrap Bootstrap files. Empty by default.WEB-INF/bootstrap/common Bootstrapped on author and public instancesWEB-INF/bootstrap/author Bootstrapped on author instance onlyWEB-INF/bootstrap/public Bootstrapped on public instance onlyWEB-INF/classes Class path for manually deployed classes.WEB-INF/config Configuration files for repository and properties

    Magnolia International Ltd.

    33

  • WEB-INF/config/default Configuration filesWEB-INF/config/default/magnolia.properties Properties such as: repository location,

    persistence manager to be used, should samplesbe bootstrapped, should installation be done inunattended mode etc.

    WEB-INF/config/default/repositories.xml defines repository configurationWEB-INF/config/default/log4j.xml Log4j logging configurationWEB-INF/config/magnoliaAuthor Properties used on author instance onlyWEB-INF/config/magnoliaPublic Properties used on public instance onlyWEB-INF/config/repo-config/typeOfPM.xml Persistence manager configuration filesWEB-INF/config/jaas.config Configuration for authentication and

    authorizationWEB-INF/lib JAR filesWEB-INF/web.xml Deployment descriptor. Describes configuration

    information for the entire web application.

    9.2. Adding the Magnolia main filter to the webapp

    The Magnolia main filter is registered in the web.xml file. The file only defines one filter:

    Magnolia global filtersmagnoliaFilterChaininfo.magnolia.cms.filters.MgnlMainFilter

    magnoliaFilterChain/*REQUESTFORWARDERROR

    Note: The Magnolia main filter will delegate the request to the Magnolia filter chain. The filter is also mapped toforward requests, which means that the Magnolia filter chain will be re-executed on internal forwards.

    Magnolia International Ltd.

    34

  • 9.3. Adding the Magnolia context listener

    In web.xml we also register one listener:

    info.magnolia.cms.servlets.MgnlServletContextListener

    The listener initializes the system, starts the repository and modules, while the filter handles all requests.

    Magnolia International Ltd.

    35

  • 10. Request processing and filters

    Magnolia CMS uses the Java filter concept introduced in the Java Servlet specification version 2.3. A filtercaptures and processes a request before it reaches a servlet. Filters typically do not themselves create responsesbut provide universal functions that can be "attached" to any type of servlet or JSP page.Filters provide the ability to encapsulate recurring tasks and modularize code. They can also transform aresponse from a servlet or a JSP page. A common task is to format data sent back to the client, such as sendingWML instead of HTML.Some functions filters can perform:

    Authentication based on user identity Logging, auditing, tracking, personalization Image conversion, scaling maps Data compression Localization

    10.1. Magnolia CMS filter chain

    The basic idea behind the filter chain is that the filters will be executed one by one until a filter decides that it canfulfill the request. This is a Magnolia CMS specific implementation of a standard Java filter chain.

    In the diagram above you can see the following filters: Context. The first filter in the filter chain is the ContextFilter. It initializes MgnlContext which is

    local to this request and available on every further filter. The context provides a lot of useful functions. Security. Checks if the request is coming from an authenticated user and if the user is authorized to

    access the requested URI.

    Magnolia International Ltd.

    36

  • Cache. The CacheFilter manages the cache. It checks if a requested resource is already stored inthe cache to avoid recreation of the resource. If the resource is in the cache, then it will be written to theresponse and the filter chain stops. If the resource is not found in the cache, then the filter passes therequest on to the CMS part of the chain.

    CMS Filter Chain. Next we arrive at the filter chain which does the page rendering and delivery. Thefilters in this sub-chain are grouped so they can share a co-bypass definition.

    Aggregation. The AggregatorFilter analyzes the request, selects the content from the repositoryand stores it in the AggregationState:

    Request URI points to Collected informationPage Content node of the requested page

    Page template

    Paragraph Content node of the requested paragraph Paragraph template

    NodeData NodeData object of the requested data, for example binary

    Rendering. Finally, the RenderingFilter is responsible for delivering the requested resource. If therequested resource is data such as a file then the data is just streamed to the response. If the requestedresource is a page, then the Rendering Filter calls the rendering engine.

    The main filter MgnlMainFilter is a single filter which in turn executes a chain of other filters. The chain is notconfigured in web.xml but in the config workspace at /server/filters.

    Magnolia International Ltd.

    37

  • In the filter configuration you can again have single filters or filter chains. A filter chain consists of a list of singlefilters represented by child nodes. A filter node has a class property which specifies the implementing class andcan optionally have an enabled property.

    If the filter is enabled, which it is by default, then the filter will be executed. Otherwise the filter will be bypassed. Afilter or a filter chain can define rules to determine when a filter should be bypassed. The configuration ofbypasses is done using Voters. For more, see Magnolia CMS core filters.

    Magnolia International Ltd.

    38

  • 11. Templating

    All Web pages created with Magnolia CMS are based on templates. Templates ensure that page structure andpresentation remain the same while the content varies from one page to another. For example, an event templatehelps you generate event pages that look and feel the same but display a different unique event each.The system generates pages by merging a template with corresponding content from the repository. The positionand inclusion of each paragraph on the page is defined by the page template. In many instances, the pagetemplate will allow authors to choose from a number of different paragraph types in a single content area.

    11.1. Pages and paragraphs

    Content nodes in the JCR hierarchy are rendered as headings, paragraphs, images, menus, forms, Javascript,meta-data and many other things. The following diagram shows the relationship between some content nodesand the corresponding page elements.Note! The diagram shows the detailed JCR view on the left. This is not how authors see content. The userinterface for authors and editors hides much of the complexity, providing a user-friendlier way to manage pagesand paragraphs.

    Magnolia International Ltd.

    39

  • Numbered items:1. An article about basketball in the New York Times Sports sections has the following page properties:

    title rendered as an H1 element on the page, "Bulls and the Thunder Make a Stand" date and author rendered on the dateline abstract to provide an introductory paragraph

    2. The next element on the page is the main collection which contains paragraphs.3. Paragraph 0 is a text paragraph ("LeBron James scored 13...") with a matching image. The image file

    and its caption and credit are stored in the document management system (DMS).4. Paragraph 00 consist of text and an optional subtitle element "THUNDER 101, LAKERS 96".5. The page ends with a footer singleton paragraph which is a kind of placeholder. It can contain content

    such as a copyright statement.

    11.2. Templating mechanism

    Magnolia CMS templating mechanism consists of the follow components: Template definition makes a template script available to the system by providing a name for it. It is the

    configuration for the template script. For instance, it defines the model class to use. Template script renders the content. The script is written in FreeMarker, JSP or a custom templating

    language. The script instructs the renderer where to place the content on the page and also containsplaceholders for content attributes such as headings and images.

    Dialog is used to enter and edit content. It is a customized HTML form with fields for entering text andmeta data and selecting images.

    Content for the page or paragraph is retrieved from the repository. It may contain text and references toimages that need to be rendered. The content node meta data assigns it to a particular templatedefinition. This way the rendering engine knows which template definition applies to the content. Throughthe definition, it can then choose the correct renderer. Note that the reference to a template definition isonly a suggestion. It is also possible to use something else to render the content. You might define analternative template when rendering content for a mobile device, for example.

    Magnolia International Ltd.

    40

  • 11.3. Component relations

    Below you find a more detailed map of relationships between the components that make up the templatemechanism. Starting at the top left corner, a template definition defines the template script used to render thecontent. The location of the script is given in the templatePath property. The template definition also assigns adialog definition in the dialog property. The dialog definition is a group of configuration nodes just like thetemplate definition. It defines what tabs and fields should be present in the dialog.The template definition further defines a modelClass. Model is a Java program that holds your business logic.The model can do any task required such as execute a Google search or calculate an insurance policy. It holdsthe results of the logic execution and passes them to a renderer.

    Magnolia International Ltd.

    41

  • The renderer includes the results on the page as instructed by the template script. The script tells the rendererwhere to place the content. It contains placeholders for content attributes such as headings, images and theresults of the business logic execution.A Web page is the output of the rendering process where template and content are combined.

    11.4. Templating languages

    The system provides two renderers out-of-the-box: JSP and Freemarker.JSP stands for Java Server Pages. It is an extension of Java Servlet technology for combining Java server-sideprograms and HTML.

    Magnolia International Ltd.

    42

  • Writing a Magnolia CMS paragraph in JSP:

    ${content.title} ${content.text}

    With Magnolia CMS 4.0, we added support for Freemarker for several reasons: not only for its flexibility, cleanersyntax and better error reporting but also because it does not depend on the file system; templates don't have tobe extracted to the file system so they can easily be stored in the repository.Writing the same paragraph in Freemarker:

    [#if content.image?has_content]

    [/#if][#if content.title?has_content]

    ${content.title}[/#if]${content.text!""}

    You can mix and match templates and paragraphs using both templating languages at will. You can also useanother templating language. If a renderer for your language is available, it is likely that you can incorporate it intoMagnolia CMS. This allows you to use a templating language that you are already familiar with.

    11.5. Tag library

    The Magnolia CMS tag library allows developers to customize the authoring environment and create templates ina fast, efficient and re-usable way. The system additionally supports third-party tag libraries such as JSTL tominimize the amount of code developers have to write.

    Magnolia International Ltd.

    43

  • Most important tags: mainBar. Displays a toolbar that allows you to change page properties and switch to the preview mode.

    This tag can also add CSS and JavaScript links on the page if not previously defined but it isrecommended to you add the cms:links tag to the header of the page instead. CSS links are not validinside the HTML body element.

    [@cms.mainBar label="Page Info" dialog="stkHomeProperties" /]

    newBar. Displays a toolbar that allows you to create new paragraphs. The list of available paragraphs ispassed as a list.

    [@cms.newBar contentNodeCollectionName="mainColumnParagraphs"paragraph="samplesTextImage,samplesDownload,samplesLink" /]

    editBar. Displays a toolbar that allows you to edit a paragraph. This tag is often used withincontentNodeIterator, which in turn will set all relevant parameters automatically.

    [@cms.editBar /]

    contentNodeIterator. Iterates over a contentNode collection. This tag is used whenever you want toloop over content, typically paragraphs. Parameter contentNodeCollectionName contains the name ofthe contentNode you are looping over. The contentNodeCollectionName is created in the first place byproviding the name to a newBar. This will result in elements being created within that contentNode, andallows you to loop over them later.

    [@cms.contentNodeIterator contentNodeCollectionName="main"][@cms.includeTemplate /]

    [/@cms.contentNodeIterator]

    includeTemplate. Delegates the task of rendering a paragraph to an appropriate ParagraphRendereror includes JSP. When used within contentNodeIterator the parameters are provided automatically bythe loop.

    [@cms.includeTemplate contentNode=content.footer /]

    Magnolia International Ltd.

    44

  • 11.6. Example of CMS tags in use

    Here is an example how tags are rendered.1. The mainBar tag creates a toolbar at the top of the page for setting page properties.2. The main area of the page includes a contentNodeIterator tag. It looks for any paragraphs that

    reside inside the main area and includes their paragraph scripts using the includeTemplate tag. Notethat the paragraph with the basketball players is not rendered by the page script but the includedparagraph script below it. The editBar associated with this paragraph is added in the paragraph script,not in the page script.

    3. A newBar creates a toolbar that allows authors to add new paragraphs on the page.4. The footer section also uses the includeTemplate tag. It calls another paragraph script (not

    displayed) that creates navigation links and a copyright statement.

    Magnolia International Ltd.

    45

  • 11.7. Templating support objects

    These objects are available to template scripts to simplify development.

    Object Purposecontent Current content node exposed as a map like cms:setNode.page or actpage Current page exposed as a map like cms:setNode. This attribute is called actpage in

    JSP because the name page is reserved.def Current RenderableDefinition (template or paragraph definition object)model JavaBean created by the renderer based on a modelClass defined in the paragraph or

    template definition. The current content, definition and the parent model are passed to theconstructor.

    actionResult The result of the model's execute method. This string can be used to determine thetemplate (in the definition) or in the template itself.

    mgnl An object providing access to various components and utility methods, for example tocreate links. See MagnoliaTemplatingUtilities.

    ctx Current Context. Depending on the type of request, a different implementation will beused, but for a web request to a page, this will be a WebContext instance. In a webrequest, you can use ${ctx.contextPath} to get the context path corresponding tothe current request.

    state Current AggregationState.stk Provides access to STK templatesi18n Messages from the current message bundle like the "Read on" message. i18n["key"]

    Magnolia International Ltd.

    46

  • 12. Dialogs

    The authoring system uses dialogs for content contribution and control. A dialog is an HTML form with input fields.Authors type content into the input fields and the dialog stores it in the repository. In addition to content entry, thesystem provides standard dialogs for page properties, data nodes, users, roles, workflow notifications and manyother editable items. It's a very agile mechanism; you can create your own dialogs and customize the standarddialogs.

    12.1. Tabs and controls

    Dialogs are assembled of controls, grouped into tabs. Text and Image is a typical content-editing dialog. It hastwo tabs: "Text" and "Image". The Text tab has a simple text box control for entering a subheading and a moreversatile rich-text control for paragraph body text. Note how internationalization support is enabled in this dialog:the field label "(en)" indicates that English language content should be entered.

    Magnolia International Ltd.

    47

  • The second tab, "Image", allows you to select an image to accompany the text. An option button (radio button)control is used to choose between uploading the image from the local computer and selecting it from thedocument management system. For more examples controls available in Magnolia CMS, see the list of availablecontrols on the documentation site.

    12.2. Dialog configuration

    A typical Magnolia CMS installation includes a standard set of dialogs. In many cases it is not necessary to createa new dialog from scratch; you can copy or extend an existing dialog and adapt it to your needs. Sample dialogsare provided with the Standard Templating Kit, Templating and Samples modules.A dialog definition defines the dialog's tabs and fields. Configuring a dialog involves three steps: create a dialogdefinition, map the dialog to a paragraph and. add the paragraph on a page.

    Magnolia International Ltd.

    48

  • 12.2.1. Create a dialog definition

    Below is the dialog definition for Text and Image.1. stkTextImage is the internal name used when referring to this dialog from a paragraph

    definition. i18nBasename defines a message bundle. The bundle is a collection of properties files insidethe module JAR that contain default labels for dialogs and fields. A reference to a property will retrievethe matching label. In this case, thekey dialogs.paragraphs.content.stkTextImage.tabText.label retrieves the dialog title"Text and Image". Storing field labels in a property file has the advantage that you can hand the file to atranslator when a new UI language is needed. Alternatively, you can type a label here.

    2. tabText is the first tab in the dialog.3. subtitle is the first field on the tab. It is an edit control, rendered as a text box (see screenshot

    above). A description is displayed below the field. i18n is enabled which means a language suffix(en, de, fr...) is displayed next to the field label and the dialog stores language specific content. Insteadof looking up the label from a properties file, a hand-typed string "Subheading" is used here forillustration purposes.

    4. text is a rich text edit control. It's a very common control used in many dialogs. This control has manyconfiguration options. To ensure that all rich text edit controls are configured the same way, we define itonce in the generic controls folder and reference when needed.

    Magnolia International Ltd.

    49

  • 12.2.2. Map the dialog to a paragraph

    Next, connect a paragraph definition to the dialog definition to make sure the correct dialog is opened when theuser clicks Edit in the editBar. The stkTextImage paragraph definition refers to the its counterpart by thedialog's internal name stkTextImage:

    12.2.3. Add the paragraph on a page

    Since the matching dialog is identified in the paragraph definition, the paragraph script doesn't need to know thisdetail. The script can render a generic editBar on the page. The reference between the paragraph definition andthe dialog definition takes care of opening the correct dialog.

    [#assign cms=JspTaglibs["cms-taglib"]][#include "/templating-kit/paragraphs/macros/image.ftl"/][#include "/templating-kit/paragraphs/macros/tocMarkup.ftl"/]

    [@tocMarkup model content /]

    [#if mgnl.editMode]

    [@cms.editBar /]

    [/#if]

    [#if content.subtitle?has_content]${content.subtitle}[/#if]

    [@image image=model.image! imageClass=model.imageClass/]

    [#if content.text?has_content]${stk.decode(content).text}

    [/#if]

    Magnolia International Ltd.

    50

  • 13. Best-practice Standard Templating Kit

    The Standard Templating Kit is a best-practice framework for creating websites. It builds upon the generictemplating mechanism described above. The kit ships with configurable, production-ready templates for commonuse cases such as articles, news, events, site-maps and image galleries, while letting developers and creativedesigners build completely custom sites. Templates can be written in JSP and Freemarker or another templatinglanguage.

    13.1. Contents

    Standard Templating Kit includes: Reusable paragraphs A mechanism for assembling page templates through definition rather than coding. A mechanism for creating custom paragraphs without affecting or even touching the page templates that

    use them. A set of use case driven page templates which can be used as such, modified or replaced with your own

    templates. Clear and clean separation of HTML, client-side functionality (jQuery), content (JCR), business logic

    (Java) and design (CSS). A static HTML prototype is provided for designers who prefer to start with CSSand a basic HTML wire-frame.

    Support for multiple site configurations

    13.2. Benefits

    Out-of-the-box solution. The use case driven page templates shipped with the kit provide a quick startto building your website. The kit gives you a significant head start since much of what you need isalready provided. Less effort generally means you will be faster but more importantly it means yourproject will be more predictable. You have less uncertainty, which for project managers means less risk.

    Use case based templates. Templates and paragraphs included in the kit are all based on real-life usecases. Templates include home, section, search, news, events, contact form, article and many more.Numerous ready to go live paragraphs are also available such as content paragraphs, teasers, stages,promos, event lists and more.

    Configurable layout and style. The look and feel of the website is controlled mainly by a single CSSfile. Since the HTML structure is designed to be styled by CSS, the look and feel of the site can bechanged without touching the templates. And since CSS is configured in the site configuration, you cancreate a custom CSS for each site.

    Role-based development. Designers and CSS developers don't necessarily need to know anythingabout Magnolia CMS in order to create a compatible a site design. They can start with the static HTMLprototype shipped with the system. From the prototype they can pick an HTML structure that is a closematch to their original design and modify it further. Style sheets are also provided.

    Accessibility. The generated HTML adheres to W3C WCAG2m and German BITV accessibilitystandards. Invisible navigation messages for vision-impaired users are included.

    Magnolia International Ltd.

    51

  • Extensibility. As the template and model are separated, you can modify the templates or extend themodel. Many aspects can be configured in the template or site definitions without writing code. Forexample, you can define paragraphs that are available for individual page templates and theirpositioning.

    13.3. STK components

    The STK consist of: Site. A site is a combination of web pages, CSS, resources (images, Javascript) and an associated site

    definition. Theme. A theme gives the site its visual identity through the use of images, colors and typography. A

    theme consists of Cascading Style Sheets (CSS), Javascript files, and an imaging configuration whichtells the Imaging module how to resize and crop images for a particular page or paragraph. MagnoliaCMS ships with an example theme called "pop". You can see it in action on the demonstration sites (seebelow).

    Templates. STK templates are normal Magnolia CMS templates but make use of the template definitionmechanism. Thanks to this, all templates (Home, Section, Article...) use the same base.

    Digital asset management (DAM) support. You can place images and videos on pages by uploadingthem from the user's computer or by selecting from the built-in document management system. Both ofthese default mechanisms can be enabled in the site definition. If you want to use your own mechanism,for example to get images from an external server, you can plug in a custom image processor.

    13.4. Site definition

    A site definition applies templates, themes and internationalization support to your site. It consists of: Template prototype. Is a base definition of a template from which all concrete templates (Home,

    Section, Article...) inherit. Template availability. Registration of available templates.

    Magnolia International Ltd.

    52

  • Internationalization and localization (i18n). Enabling i18n support in the site definition allows authorsto write foreign-language content. When enabled, the mainBar has a language drop-down. Dialogsdisplay the language identifier (en, fr, de...) to make it clear what language should be entered. Foreign-language content is served to visitors at a specific URL, such as www.mywebsite.com/de/article.html. Redirecting visitors to the language-specific URL is configured in the web server.

    Domains. Mapping of a domain name to a site. Mappings. Mapping of the requested URI to a repository. Here you can use prefixes and handles. For

    example, if a prefix such as dms is detected in the request the requested asset is served from therepository given in the repository property. A handle can be used in building the URI. For example, ifthe requested URL contains /demo-project alone, map it to the website repository. If it contains/demo-project/docs, map it to the dms repository.

    The Standard Templating Kit ships with two fully-functional demonstration sites: Demo project shows how templates work in realistic site context. It has working examples of article,

    news, event and many other page templates as well as paragraphs such as video, teaser and stage. Author instance username/password: superuser/superuser Public instance

    Demo features shows the same templates grouped categorically: content templates, special templates,aggregation paragraphs, areas, sections and modules.

    Author instance username/password: superuser/superuser Public instance

    Magnolia International Ltd.

    53

  • 13.5. Areas

    The page templates shipped with the Standard Templating Kit organize the page layout using areas. These arecontrollable blocks, typically rendered as div elements, that help you customize the template structure.Typically each area is wrapped in a div element, having a correspondingly name ID attribute, for example mainarea has id=main.

    Note: An area is not the same as a paragraph. Paragraph is a content element with an associated paragraphdefinition while areas are structural elements in the template script. In fact, areas are dynamic include directiveswhich together compose a single template script.

    Magnolia International Ltd.

    54

  • The following diagram illustrates some key elements you will find on a page based on the article pagetemplate. The box captions indicate div element ID attributes. For example, the element that renders the verticalnavigation on the left is .

    Note! This is not a complete set of areas. There are further smaller div elements to handle logo and breadcrumbplacement, for example. Other page templates again offer drastically different layouts, using elements such asstages and platforms to promote content.

    Magnolia International Ltd.

    55

  • 13.6. Template inclusion

    Templates at higher level can include lower-level templates using Freemarker's #include directive. Thisapproach allows you to modularize and re-purpose your template scripts. It also has the benefit of keeping scriptsbrief and readable.The following diagram shows how inclusion works. The page template has a header area. Inside the header divelement there is a Freemarker #include directive that calls another template script, header.ftl. The headertemplate script in turn includes two further templates to render branding and horizontal navigation.

    1. Includes the template script configured in template definition (configured either in the prototype oroverwritten in the concrete template).

    2. Template script, referenced from the template definition.

    Magnolia International Ltd.

    56

  • 13.7. Customization

    This dynamic approach allows you to combine your own templates with those of STK. Use the STK templates asmuch as you can to speed up development. When you can't move further without customizing, create your owntemplate.Three customization options:

    Change the main template used by all STK templates if you want to change the main HTML structure.This is configured in /prototype/templatePath. The default value is /templating-kit/templates/main.ftl.

    Reconfigure template scripts used for specific areas.All further dynamic includes can continue to be reused elsewhere, and in your custom template if you need them.In most cases you would copy an existing template. In the site definition, override the used template by settingthe template attribute to the customized one.

    Tip: When using Freemarker, you don't need to put the template script in the template workspace. You can loadthem from your module JAR. This is what we recommend for production projects.

    Magnolia International Ltd.

    57

  • 13.7.1. Template prototype

    The prototype site definition is a good entry point for understanding the STK. It is a "fallback object" for alltemplate definitions of a site. Any template will extend the prototype, which means any template configuration thatyou don't define in the template is automatically inherited from the prototype. It is likely that you can takeadvantage of the prototype templates and reuse them for your custom site with small changes.

    Magnolia International Ltd.

    58

  • Examples of template configuration options available in the prototype site definition:

    Path DescriptionhtmlHeader Configures the template used in the inner part of element.navigation Configures navigation. The static HTML prototype includes a page that shows you how the

    various navigation menus look at all depths. It allows the CSS designer to see at single glancewhether test CSS is correct.

    navigation/horizontal

    Horizontal navigation, including the number of levels and template script used.

    navigation/vertical

    Vertical navigation, including the number of levels and template script used.

    header Page header, including the branding, section header and stage.breadcrumb Breadcrumb displays the navigated path to the user.mainArea Configuration of the main area. In the prototype the area is used for basic content templates

    such as articlesextrasArea Extras area is typically located on the right hand side. This configuration is site-wide and

    contains a list of paragraphs available as extras.footer Configuration of the footer.

    Magnolia International Ltd.

    59

  • This is what happens when a template prototype is merged with a concrete template:1. Template prototype is the basis.2. Concrete template definition adds and overrides.3. The result is exposed as the template definition (def) to the template script

    stkHome defines which paragraphs are available in the mainArea. It also uses a custom template script forthe mainArea and disables the extrasArea. The prototype defines the main template (main.ftl) and pre-configures the main and extras areas.

    Magnolia International Ltd.

    60

  • 13.7.2. Static HTML prototype

    The STK bundle (download here) ships with a static HTML prototype. It is a collection of STK page templatesdelivered as stand-alone HTML files. Referenced CSS and images are also included. The static prototype isaimed at creative teams who don't know how Magnolia CMS works or have no particular desire to learn it. Itallows designers to work on positioning, typography and color outside of Magnolia CMS, using their own tools, intheir own environment.You can (and should) use the HTML prototype to develop your CSS. The advantages of this approach include:

    See all possible variations of an element instantly Perform CSS programming independent of Magnolia CMS Better testability Faster turnaround

    Whenever Magnolia enhances the STK, we add new HTML to the static prototype first. The static HTML is thentested on all supported browsers. Once the HTML has been perfected, templates are created.

    Magnolia International Ltd.

    61

  • The static prototype contains an index page which serves as the starting point for paragraph and page templatesprovided with the STK.

    Magnolia International Ltd.

    62

  • Navigation at all levels is also available at a single glance. Developing a CSS against this view saves a lot of timewhen you can see all variations right away.

    Magnolia International Ltd.

    63

  • 13.8. Design with CSS

    The modular templating approach gives creative designers free hands. Positioning, layout and styling isconvenient with CSS given that each key page element can have its own template script and is enclosed in a divelement that has an ID attribute.

    Magnolia CMS supports role-based development by letting everyone work on what they are good at. Designerscan change the appearance of a page without having to change a template. Likewise, templates do not becomecluttered with design fragments.

    13.9. Layout and grid

    The template layouts are dynamic. The default layout of three fixed columns is optimized for a screen resolutionof 1024. The grid is extremely flexible and offers easy grid variations.The dynamic template layouts change on the fly, to adapt to the user's viewport:

    For larger screens, with a minimum width of 1200 px an extra style: wide.css is added. The effect of thisis that an additional promo sidebar, is displayed on the right of the screen.

    For medium screens, width 981-1199 px, the layout accommodates the narrower viewport by displayingpromo sidebar beneath the main content.

    For small screens, with a maximum width of 980px an extra style: small.css is added. The main areadisplays two columns of teasers instead of three.

    Magnolia International Ltd.

    64

  • Wide: min. width 1200 px Medium: 981 to 1199 px Small: max. width 980 px

    The technique used to achieve this is CSS media queries and JavaScript. For older browsers that do notrecognize JavaScript it is completely unobtrusive and the default CSS resolution is 1024 x 768 px.

    Magnolia International Ltd.

    65

  • 13.9.1. HTML structure

    HTML structure, as provided by the default template:

    Magnolia International Ltd.

    66

  • 13.10. Body IDs and classes

    The body ID is an attribute on the body HTML element, for example . It represents the pagetype such as Home, Section, Article and so on. The body ID of a page is defined in its template definition. Thismechanism allows you to style pages differently while still using a single CSS file.Some example of body IDs are:

    home section article image-gallery

    The body class attribute is used to control the number of columns and the column width. It provides for instanceinformation about whether we have vertical navigation or not.

    The Body Classes are automatically generated by the STK system. In the template definition a propertybodyClass can be set. This overwrites the auto generated body class value.Some body classes are:

    nav-col-subcol: Three-column setup with navigation on the left and a small extras area. nav-col: Two-column setup with a navigation on the left and one large content column. col-float3: One large column and three floating teasers. Home page is an example of this.

    13.10.1. CSS configuration

    Style sheets used with STK templates are stored as content nodes within Magnolia CMS. This allows you tomanage them in AdminCentral instead of having to work at the file system level.STK ships with a collection of style sheets targeted to different viewports and media. You can see these sheets atwork on the demonstration sites and the static HTML prototype.

    Magnolia International Ltd.

    67

  • Referencing a style sheet works like this:1. Style sheets are stored as content nodes under Templating Kit > Resources. They are organized into

    folders according to the theme they belong. In this example, the "pop" theme has five style sheets aimedat different media and viewports.

    2. In Templating Kit > Themes, a theme definition contains a link to each sheet. It also defines thetargeted media type (screen, print etc).

    Note that in the media property you can use CSS3 media queries to test the features of the outputdevice. The sheet is applied if the test evaluates to true. In the example above we evaluate the minimumwidth of the viewport before applying the wide sheet.

    Magnolia International Ltd.

    68

  • 3. In the htmlHeader page template, a Freemarker #list directive collects the style sheets from the poptheme. It creates link elements and writes them in the page head element.

    [#list model.site.theme.cssFiles as cssFile]

    [/#list]

    Tip: In real production projects it is recommended that CSS are stored in the module JAR. They have to reside inthe mgnl-resources folder. In that case the link property will point to /.resources/pathToCss.

    13.11. Learn more

    Check out these videos of STK templates in action: Introduction to STK and basic demonstration. Glossary, grouped teaser paragraphs, events overview, FAQ

    Examples of diverse sites built wit