Surf Platform - Freemarker Template and JavaScript API

From alfrescowiki

Jump to: navigation, search

NOTE: This page describes the Alfresco Surf Platform which is included in Alfresco 3.0, 3.1 and 3.2.

If you are looking for information about Alfresco 3.3, please visit Spring Surf.


Note: This document describes an API which is available in the presentation tier when using Alfresco Surf. The objects and methods described herein are available to templates and components within an Alfresco Surf application and not available for repository tier Web Scripts.

Overview

When building new presentation templates or web components, developers may choose to use Alfresco's Freemarker and JavaScript technologies. These are the default and preferred way to build high performance and lightweight web parts. They are easy to build and require no server restarts.

The availability of these APIs speeds the time to develop new functionality. Most Surf platform features are available as root scope JavaScript and FreeMarker objects. Developers are able to work with the full range of the Surf platform object model, the request context, users, remote connections, and credential management.

The Freemarker Template API and the JavaScript API use a common object model. This means that the objects available to the JavaScript API are very similar (in most places, identical) to those made availble by the Freemarker API. There are some minor differences that are noted in their respective sections below. It is recommended though that the standard development pattern of logic work being performed in JavaScript and presentation work being performed in FreeMarker should be followed where possible.

Surf Platform Root-Scoped API

The Surf Platform Freemarker Template Processor provides capabilities similar to that provided by Alfresco's FreeMarker Engine. However it does not provide direct access to Alfresco repository concepts such as Nodes and Propetries that developers of repository tier Web Scripts will be familar with.

Similarly, the Surf Platform Web Script runtime extends the capabilities that are already provided by Alfresco's Web Script runtime. These are covered in great depth in the Web Scripts and Web Script Runtimes pages. There, you will find examples of how to build your own Web Scripts.

The Surf platform extends the basic Alfresco templating and scripting capabilities and then provides additional web-tier related root-scoped objects.

Root-scoped Objects

The Surf platform root-scoped objects are:

context
The request context of the current page.
user
The current user.
content
The current content instance (available if the dispatcher is rendering a page for a given content object id).
page
Information relating to the current page object.
theme 
The current theme ID.
instance
The currently rendering model object (along with rendering context).
sitedata
Utility for working with the Surf platform object model.
remote
The Web Script Framework remote helper object.
locale
The current Locale for the user request thread - as a string in Java Locale format.
htmlid
The page unique HTML ID for the current component if any.
url
URL model for the current page request.
head
Concatenated component .head template output.


context

The request context object provides the following properties:

id
The internally managed id for the current request.
pageId
The id of the page being rendered.
page
The page object being rendered.
templateId
The id of the template being rendered.
template
The template object being rendered.
user
The current user
themeId
The current theme id.
theme
The current theme object.
formatId
The format id for the current request.
properties
Associative array of all context values.
authenticated
Returns true if there is a non-guest current user.
externalAuthentication
Returns true if external authentication such as NTLM is being used to manage the user.

If the dispatcher is rendering a page for a given content object id, the following objects will additionally be available:

contentId
The id of the content being rendered
content
The content being rendered.

For example:

var pageTitle = context.page.title;
var userFullName = context.user.fullName;
var contentTitle = context.content.properties["title"];
var customValue = context.properties["customValue"];


user

The user object provides the following properties:

properties
An associative array of user properties.
id
The user identifier.
name
The Principal name (most commonly, this will be the same as the user id).
fullName
The user's full name (for example, Joe Dwight Smith).
firstName
The user's first name (Joe).
middleName
The user's middle name (Dwight).
lastName
The user's last name (Smith).
email
The user's email.
organization
The user's organization.
jobTitle
The user's job title.
location
The user's location.
biography
The user's biography.
telephone
The user's telephone entry.
mobilePhone
The user's mobile phone entry.
skype
The user's skype id.
instantMsg
The user's instant message id.
companyPostcode
The user's company post code.
companyTelephone
The user's company telephone.
companyFax
The user's company fax entry.
companyEmail
The user's company email.
companyAddress1
The user's company address entry 1.
companyAddress2
The user's company address entry 2.
companyAddress3
The user's company address entry 3.

The user object provides the following methods:

save()
Saves changes to the users properties - if supported by the User object implementation.
getUser(userId)
Retrieve a user object with populated details for the given user Id.

For example:

<#if user.location == "Boston">
   <p>Welcome to the Red Sox appreciation page, ${user.firstName}!</p>
</#if>


content

NOTE: Only available if an object ID is provided as part of the page URL.

The content object provides the following properties:

id
The id of the content object.
typeId
The type id of the content object.
properties
An associative array of properties about the object.

The following properties are metadata fields about the object:

timestamp
The time (long) when the object was loaded.
endpointId
The id of the endpoint from which the object was loaded.
isLoaded
Whether the object successfully loaded.
statusCode
Status code from the attempt to load the object.
statusMessage
Status message from the attempt to load the object.

The following properties contain the payload of the document itself:

text
The content of the selected object as text
xml
The content of the selected object as xml

For example, you can work with metadata about the currently selected object as follows:

var id = content.id;
var typeId = content.typeId;
var endpointId = content.endpointId;
var timestamp = content.timestamp;
var isLoaded = content.isLoaded;
var statusCode = content.statusCode;
var statusMessage = content.statusMessage;
var customData = content.properties["cm:customData"];

You can also write components that work with the data of the object. This is particularly useful if you're dispatching from XML of Web Form based objects:

var text = content.text;
var xml = context.xml;

// parse the xml and load properties into our model
var e4x = new XML(content.xml);
model.productName = e4x.*::name.toString();
model.productDescription = e4x.*::description.toString();

Where the XML could be the following:

<pr:product xmlns:alf="http://www.alfresco.org"
            xmlns:chiba="http://chiba.sourceforge.net/xforms"
            xmlns:ev="http://www.w3.org/2001/xml-events"
            xmlns:pr="http://www.alfresco.org/alfresco/pr"
            xmlns:xf="http://www.w3.org/2002/xforms"
            xmlns:xhtml="http://www.w3.org/1999/xhtml"
            xmlns:xs="http://www.w3.org/2001/XMLSchema"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

   <pr:name>Demo Product 1</pr:name>
   <pr:description>Demo Product 1</pr:description>

</pr:product>


instance

The instance object provides the following properties:

object
The currently executing object (page, template or component).
id
The id of the currently executing object.
htmlId
The page unique HTML id of the currently executing object.
properties
An associative array of properties about the currently rendering object.

The instance object provides the following methods:

getParameterNames()
Returns a String[] of the names of the request parameters.
getParameter(String name)
Returns the parameter value for the given parameter name.
getParameters()
Returns an associative Array of the request parameter name/value pairs.


page

NOTE: Only available within the context of a page render.

The page object provides the following properties:

url
The url helper object.
id
Page object ID.
title
Page definition title.
titleId
Page definition title I18N message id.
description
Page definition description.
descriptionId
Page definition description I18N message id..
theme
Theme ID.
properties
Custom page definition properties map, for example page.properties["abc"].


url

The url object provides the following properties:

context
Page root context path, for example /share.
servletContext
Page root context path and servlet path, for example /share/page.
uri
Page URI (no URL arguments), for example /share/page/mylogin.
url
Complete page URL, for example /share/page/mylogin?user=test.
queryString
Query string from the URL, for example user=test&a=1.
args
Map of URL argument name/value pairs.


sitedata

The sitedata object provides the following framework properties:

rootPage
Root page object for the web site/application.
siteConfiguration
Configuration object for the web site/application.

The following properties provide arrays of all objects of a given type:

chrome
Array of all Chrome objects.
components
Array of all Component objects.
componentTypes
Array of all ComponentType objects.
configurations
Array of all Configuration objects.
contentAssociations
Array of all ContentAssociation objects.
pages
Array of all Page objects.
pageTypes
Array of all PageType objects.
pageAssociations
Array of all PageAssociation objects.
templates
Array of all Template objects.
templateTypes
Array of all TemplateType objects.
themes
Array of all Theme objects.

The following properties provide associative arrays (or maps) of all instances for a given object type. These maps are keyed by object id:

chromeMap
Associative array of all Chrome objects.
componentsMap
Associative array of all Component objects.
componentTypesMap
Associative array of all ComponentType objects.
configurationsMap
Associative array of all Configuration objects.
contentAssociationsMap
Associative array of all ContentAssociation objects.
pagesMap
Associative array of all Page objects.
pageTypesMap
Associative array of all PageType objects.
pageAssociationsMap
Associative array of all PageAssociation objects.
templatesMap
Associative array of all Template objects.
templateTypesMap
Associative array of all TemplateType objects.
themesMap
Associative array of all Theme objects.

The following generic lookup methods are also available, if you are looking for components it is generally much faster to use the specific findComponents() method as detailed below:

getObjects(objectTypeId)
Array of all objects of the given type.
getObjectsMap(objectTypeId)
Associative array of all objects of the given type.

The following methods allow you to create new objects:

newChrome()
Instantiates a new Chrome.
newComponent()
Instantiates a new Component.
newComponent(componentTypeId)
Instantiates a new Component with the given ComponentType id.
newComponent(componentTypeId, title, description)
Instantiates a new Component with the given ComponentType id, title and description.
newComponentType()
Instantiates a new ComponentType.
newConfiguration()
Instantiates a new Configuration.
newConfiguration(sourceId)
Instantiates a new Configuration bound to the given source id.
newContentAssociation()
Instantiates a new Content Association.
newPage()
Instantiates a new Page.
newPage(title, description)
Instantiates a new Page with the given title and description.
newPageAssociation()
Instantiates a new Page Association.
newPageType(pageTypeId)
Instantiates a new Page Type.
newTemplate()
Instantiates a new Template.
newTemplate(templateType)
Instantiates a new Template instance of the given template type.
newTemplate(templateTypeId, title, description)
Instantiates a new Template instance of the given template type, title and description.
newTemplateType(templateTypeId)
Instantiates a new Template Type with the given id.

The following generic object creation method is also available:

newObject(objectId, objectTypeId)
Instantiates a new object of the given type

The following methods look up objects and return arrays of results. An AND operator is applied across all supplied parameters. If a parameter is null, it is not included in the lookup.

findComponents(scopeId, sourceId, regionId, componentTypeId)
Finds all Component instances whose bindings match the given scope, source object, region and component type. The component type should be left as null for the fastest lookup performance.
findChildPageAssociations(sourceId, destId)
Finds all PageAssociation instances of type child between the given source and destination pages.
findPageAssociations(sourceId, destId, assocType)
Finds all PageAssociation instances between the given source and destination pages of the given association type (that is, child).
findChildPages(sourceId)
Finds all child page objects for the given top level page id.
findContentAssociations(sourceId, destId, assocType, formatId)
Finds all ContentAssociation instances whose bindings match the given source id, dest id, association type and format.

The following methods look up objects and return maps of results. An AND operator is applied across all supplied parameters. If a parameter is null, it is not included in the lookup.

findComponentsMap(scopeId, sourceId, regionId, componentTypeId)
Finds all Component instances whose bindings match the given scope, source object, region, and component type. The component type should be left as null for the fastest lookup performance.
findPageAssociationsMap(sourceId, destId, assocType)
Finds all PageAssociation instances between the given source and destination pages of the given association type (that is, child).
findContentAssociationsMap(sourceId, destId, assocType, formatId)
Finds all ContentAssociation instances whose bindings match the given source id, dest id, association type and format.
findTemplatesMap(pageId)
Finds all templates that are bound to the given page.

The following methods return a single object. An AND operator is applied across all supplied parameters. If a parameter is null, it is not included in the lookup. If multiple objects result from the lookup, the first one is returned:

findConfiguration(sourceId)
Returns a Configuration instance bound to the given sourceId.
findTemplate(pageId)
Returns the default Template instance bound to a given page.
findTemplate(pageId, formatId)
Returns the Template instance bound to a given page for a specific format.

The following methods are used to bind objects together. These are used to create association objects and to stamp binding parameters onto objects:

associateComponent(componentId, scopeId, sourceId, regionId)
Binds a given component to specified scope, source object, and region.
associateTemplate(templateId, pageId)
Binds the default template to a page.
associateTemplate(templateId, pageId, formatId)
Binds a template to a page for a given format id.
associatePage(sourceId, destId)
Associates a source page to a child page.
associateContent(contentId, pageId, formatId)
Associates a content id to a page for a given format id.
associateContentType(contentTypeId, pageId, formatId)
Associates a content type id to a page for a given format id.

The following methods are used to unbind objects from one another. They are used to remove association objects and to clear binding parameters on objects:

unassociateComponent(componentId)
Unbinds a given component so that it is uncoupled from a scope, source object, and region.
unassociateTemplate(pageId)
Unbinds the default template from a page.
unassociateTemplate(pageId, formatId)
Unbinds a template from a page for a given format id.
unassociatePage(sourceId, destId)
Unassociates a source page from a child page.
unassociateContent(contentId, pageId, formatId)
Unassociates a content id from a page for a given format id.
unassociateContentType(contentTypeId, pageId, formatId)
Unassociates a content type id from a page for a given format id.

The following methods can be used to look up individual objects:

getObject(objectTypeId, objectId)
Returns a single object with the given object type id and object id
getChrome(objectId)
Returns a Chrome instance with the given object id
getComponent(objectId)
Returns a Component instance with the given object id
getComponent(scope, regionId, sourceId)
Returns a Component instance bound to the given scope, region id and source id
getComponentType(objectId)
Returns a ComponentType instance with the given object id
getConfiguration(objectId)
Returns a Configuration instance with the given object id
getContentAssociation(objectId)
Returns a ContentAssociation instance with the given object id
getPage(objectId)
Returns a Page instance with the given object id
getPageType(objectId)
Returns a PageType instance with the given object id
getPageAssociation(objectId)
Returns a PageAssociation instance with the given object id
getTemplate(objectId)
Returns a Template instance with the given object id
getTemplateType(objectId)
Returns a TemplateType instance with the given object id
getTheme(objectId)
Returns a Theme instance with the given object id

For example:

// create two pages
var page1 = sitedata.newPage("My First Product Page", "First Description");
var page2 = sitedata.newPage("My Second Product Page", "Second Description");

// associate both pages to the site's root page
sitedata.associatePage(sitedata.rootPage.id, page1.id);
sitedata.associatePage(sitedata.rootPage.id, page2.id);

// create a new template instance of type "product_display_template"
var template1 = sitedata.getObject("product_display_template");

// bind both pages to this template for their "default" format
sitedata.associateTemplate(template1.id, page1.id);
sitedata.associateTemplate(template1.id, page2.id, "default");

// create a component instance
var component1 = sitedata.newComponent("pdfViewer", "PDF Viewer", "Description");

// bind component into both pages at once by setting to template scope
sitedata.associateComponent(component1.id, "template", template1.id, "viewer");


remote

The remote object provides the following properties:

endpointIds
A String[] of available endpoint ids.

The remote object provides the following methods:

connect
Provides a connector to the default endpoint.
connect(endpointId)
Provides a connector to the given endpoint ID.
call(uri)
Invoke a specific URI on the default endpoint - this is just a shortcut for calling remote.connect().call(uri).
getEndpointName(endpointId)
Returns the display name for an endpoint
getEndpointDescription(endpointId)
Returns the description for an endpoint
getEndpointURL(endpointId)
Returns the url for an endpoint

For example:

// get a connector to the Alfresco repository endpoint
var connector = remote.connect("alfresco");

// retrieve the web script index page
var indexHtml = connector.get("/index");

// TODO: do something with it...

Return types

Model objects

Model objects are returned from most of the query functions on sitedata. They are also bound to rendering contexts. A model object could be a component, a template, or any other object type.

Properties

By default, the following properties are available:

id
The id of the object.
title
The title of the object.
description
The description of the object.
properties
An associative array (map) of all properties on the object.

Metadata properties

The following metadata properties are available:

timestamp
The modification time of the object(long).
persisterId
The id of the persister to which the object belongs.
storagePath
The path to the file within the persister.

Persistence methods

The following persistence methods are available:

save()
Persists the model object to the store.
reload()
Reloads the model object from the store.
remove()
Removes the model object from the store.

Methods

The following methods are also available:

toXML()
Generates a user-friendly XML serialization of the object.
touch()
Touches the model file (updating its modification timestamp).
getProperty(key)
Returns the property directly from the model object.
setProperty(key, value)
Sets a property directly onto the model object.
removeProperty(key)
Removes a property from the model object.

Connectors

Connectors are retrieved via the remote object and are used to communicate with endpoints. This communication generally consists of an HTTP request followed by an appropriate Response object (JSON, XML or other format).

Properties

endpoint
The ID of the endpoint to which this connector is bound

Methods

call(uri)
Invokes a URI on the endpoint - same as calling get(uri).
get(uri)
Invokes a GET request URI on the endpoint.
post(uri, body)
Invokes a URI on the endpoint, passing the supplied body as a POST request.
post(uri, body, mimetype)
Invokes a URI on the endpoint, passing the supplied body as a POST request. The given mimetype for the content body is applied.
put(uri, body)
Invokes a URI on the endpoint, passing the supplied body as a PUT request.
put(uri, body, mimetype)
Invokes a URI on the endpoint, passing the supplied body as a PUT request. The given mimetype for the content body is applied.
del(uri)
Invokes a URI on the endpoint as DELETE request.

Response

The Response object wraps the response data, status code, status message and any exception information from a remote call.

Properties

response
The data of the response as a string.
status
Returns a ResponseStatus object wrapping the return code status, message and any exception information.

ResponseStatus

The ResponseStatus object wraps the response status code, status message and any exception information from a remote call.

Properties

message
Response status message.
code
Response status code.
codeName
Localised response status code name.
codeDescription
Localised response status code description.
exception(
Reponse status exception object - may be null.

Rendering Engines

Specific objects are available to each different types of rendering engine. There are two rendering engines that are most common: template renderers and component renderers.

Templates

The following root-scoped objects are available during the rendition of a Template:

  • sitedata - always available
  • context - always available
  • instance - always available
  • user - always available ('guest' if unauthenticated)
  • content - available if content is being dispatched
  • page - page model object
  • theme - the current theme id
  • htmlid - the html id
  • url - url info object
  • head - String of all component headers (<script> and <link> dependencies)

Custom properties of the Template object can be accessed like this:

${context.template.properties["customProperty"]}

Custom properties of the Page object can be accessed like this:

${context.page.properties["customProperty"]}

The following Surf directives are available to Freemarker Templates:

<@region id="regionName" scope="(global, template or page)" protected=true/false/>
<@component componentId="(id of component)" chrome="(id of chrome)" chromeless=true/false/>


Components

The following root-scoped objects are available during the rendition of a Component:

  • sitedata - always available
  • context - always available
  • instance - always available
  • user - always available (guest if unauthenticated)
  • content - available if content is being dispatched
  • page - page model object
  • theme - the current theme id
  • htmlid - the html id

Custom properties of the currently rendering Component can be accessed like this:

${instance.properties["customProperty"]}
Personal tools
© 2014 Alfresco Software, Inc. All Rights Reserved. Legal | Privacy | Accessibility