SlideShare une entreprise Scribd logo
1  sur  41
Introduction to Sightly and Sling Models in AEM6
Stefano Celentano
2
• What is Sightly?
• Why Sightly?
• Separation of concerns
• Comparing JSP and Sightly development
• Sightly features
• Sightly: the basics of the language
• Not a silver bullet
• Sightly and Sling Models
• An amazing combination
• Basic usage
• Learning from experience
• wcm-io and ACS Commons libraries
• Useful links
• A few hands-on examples
Summary
3
• New secure server-side HTML Templating Language introduced with AEM6 for
efficient development
• “Sightly” (meaning “pleasing to the eye”)
• “Alternative” to JSP
• Specification and TCK open sourced to GitHub
• Reference Adobe implementation donated to Apache Sling by Adobe (September
2014)
• Sightly reference implementation has been folded into Apache Sling project
• org.apache.sling.scripting.sightly
• org.apache.sling.xss
What is Sightly
4
Why Sightly: before…
5
Why Sightly: …after!
6
The standard workflow:
• Front end developers create HTML mark up, designs with all necessary client side
libraries
• (AEM) back end developers take this well formed, high-fidelity static HTML
“prototype”
• Systematically split the whole template in pieces
• Put it together again as JSP templates and components
• Add custom business logic inside JSP templates and components
This leads to well known issues:
• The process of splitting and putting together is error prone
• The process itself is time consuming
• This way of development does not provide good (and simple) separation of concerns
between UI and business logic
• As front end developers can’t easily maintain JSPs, they don’t develop new
components “inside” AEM
• They don’t directly cope with components issues in Author mode
(both visualization and UI issues)
Why Sightly: separation of concerns
7
Why Sightly: separation of concerns
8
Why Sightly: separation of concerns
9
Why Sightly: comparing JSP and Sightly
10
Why Sightly: comparing JSP and Sightly
11
Why Sightly: comparing JSP and Sightly
12
Why Sightly: comparing JSP and Sightly
13
Why Sightly: comparing JSP and Sightly
• Writing custom tag lib is not easy
• Need to mantain both Java class and TLD
• Custom tag lib lifecycle is hard to understand and difficult to integrate
inside the templates
• Have you ever effectively used it for your projects?
JSP Sightly
Based on Published Standards / Open Source?Y (*) N Y
IDE Support? Y Y/N
Officially Documented / Supported? Y Y
Documented Extension Model? Y N
Includes XSS escaping? Y (**) Y
Allows Basic Logic? Y Y
Enables Bad Coding Practices? Y N
* Some proprietary TagLibs used for interacting with CQ
** Provided by additional tag libraries
14
Why Sightly: features
• Code-less language, forcing strict separation of concerns
• Powerful extension points with the Use-API
• Automatic contextual HTML escaping and XSS protection
• Automatically removes HTML attributes if value is empty
• Reuses HTML blocks for statements
15
Sightly: the basics of the language
Expression language example:
<a href=‘‘{properties.link || ‘#’}’’ title=‘‘{properties.jcr:title}’’>
${properties.jcr:description}
</a>
Features:
- Automatic contextual HTML escaping and XSS escaping (warning!)
- Fallback value if property is empty
- Remove HTML attribute if value is empty
16
Sightly: the basics of the language
• Sightly comments
<!-- /* This will disappear from the output *-->
• Expression language
${properties.myProperty}
• They can only be used in attribute values, comments or in element content
• Standard bindings are available as in JSPs
• Block statements
<div data-sly-include=‘‘another-template.html’’></div>
17
Sightly: the basics of the language
• Expression bindings:
• ${properties}
• ${pageProperties}
• ${inheritedPageProperties}
• ${request} Sling Request
• ${resource} Sling Resource
• ${currentPage} WCM Page
• ${currentDesign} WCM Design
• ${component} WCM Component
• ${wcmmode} WCM Mode
Access properties with dot
notation ${properties.foo}
To avoid complex expressions inside
templates, Sightly does not allow
passing arguments to function call.
Only zero argument calls are allowed
from templates.
18
Sightly: the basics of the language
• Options allow to manipulate the result of an expression, or to pass
arguments to block statements
• Everything after the @ are comma separated options:
${myVar @ optionOne, optionTwo}
• Examples:
• String formatting:
${‘Page {0} of {1}’ @ format=[current, total]}
• Internationalization:
${‘Page’ @ i18n}
• Array join:
${[‘one’, ‘two’] @ join=‘; ’}
19
Sightly: the basics of the language
• Display context
• Every expression in Sightly has a display context
• Display context depends on the location within the HTML structure
• Example: text node, attribute, …
• Sightly automatically detect the context of expressions and escape them appropriately (to
prevent XSS)
This is not true for script (JS) and style (CSS) contexts
In this case we should explicitly set the context
• Example
<a href="${properties.link}" title="${properties.title}">${properties.text}</a>
Three variables, three different contexts.
No explicit context setting is required in the above cases
20
Sightly: the basics of the language
• Display context option
• The context option offers control over escaping and XSS protection
• Explicit context must be set for style contexts:
<span style="color: ${properties.color @
context='styleToken'};">...</span>
• To safely output markup (filtering out scripts)
<div>${properties.richText @ context=‘html’}</div>
uses AntiSamy policy rules
The default antisamy configuration is present at /libs/cq/xssprotection/config.xml, which can
be overlaid with your custom config within /apps.
• Adding URI validation protection to other attributes than src or href
<p data-link=‘‘${link @ context=‘uri’}’’>text</p>
21
Sightly: the basics of the language
• Most useful contexts and what they do:
• uri To display links and paths (validates URI)
• attribute Encodes HTML special characters
• text Encodes HTML special characters
• scriptString Encodes characters that would break out the string
• styleString Validates CSS tokens. Outputs nothing if it fails
• html Filters HTML to meet AntiSamy policy rules, removing what doesn’t match
• unsafe Disable all escaping and XSS protections
22
Sightly: the basics of the language
• Block statements
• To keep markup valid, block statements are defined by data-sly-* attributes
that can be added to any element on the markup
• <input data-sly-STATEMENT=‘‘foo’’ />
• Block statements can have no value, a static value, or an expression
<input data-sly-STATEMENT=‘‘${bar}’’ />
• Despite using data-attributes, block statements are all executed on the
server and no data-sly-* attribute is sent to the client!
• Sightly block statements:
• Markup inclusion: Include, Resource
• Control flow: test, list, template, call
• Markup modification: unwrap, element, attribute, text
• Object initialization: use
23
Sightly: the basics of the language
• Template and call statements
• Similar to data-sly-include
• Main difference: you can pass parameters to the included template
• Templates must be declared and called from another template
• <data-sly-template> declares a template
<template data-sly-template.header> <div> my template </div> </template>
Defines a template called header
Notice: the host element are not output by Sightly. If you call this template the only printed
mark up will be
<div> my template </div>
• <div data-sly-call=‘‘header’’></div> calls the template header defined above
• Templates can be located in a different file
• Templates accept parameters
<template data-sly-template.two=‘‘${ @ title}’’> <h1>${title}</h1> </template>
<div data-sly-call=‘‘${two @ title=properties.jcr:title}’’></div>
24
Sightly: the basics of the language
• Unwrap statement
• Removes the host element while retaining its content
<div data-sly-unwrap> <h1> Title </h1> </div>
Output: <h1> Title </h1>
• Warning!
• Use unwrap only when there’s no other way to write your template
• Prefer adding statements to existing elements
• Templates can easily become difficult to read
• Unwrap can also be subject to condition
<div class=‘‘edit-md’’ data-sly-unwrap=‘‘${wcmmode.edit}’’>
Text
</div>
Output: Text in EDIT mode
Output in PREVIEW/PUBLISH mode: <div class=‘‘edit-md’’>
Text
</div>
• Use data-sly-test to remove the element content as well
25
Sightly: the basics of the language
• Use statement: Sightly Javascript Use API. Enables a Sightly file to access
helper code written in Javascript.
• Initialize a helper objects
<div data-sly-use.logic=‘‘logic.js’’>${logic.value}</div>
Inside logic.js file
use(function()) {
return {
value: ‘‘Hello World’’
};
});
Output:
<div> Hello World </div>
• Use Javascript Use API only for very simple tasks (date formatting, text
formatting, simple conditional logic, …):
• Javascript Use API is server-side Javascript (some JS native features are not fully supported)
• Cannot be debugged
• Very hard to find errors
• It’s slow
• Very hard to write Javascript Use API code for more complex task (e.g., cycling on repository
nodes, calling external services, etc.)
26
Sightly: the basics of the language
• Use statement: Sightly Java Use API enables a Sightly file to access helper
methods in a custom Java class.
• POJO extending WCMUse class
• WCMUse has been deprecated from AEM 6.1
and replaced with WCMUsePojo which uses
the new Sightly API from Apache Sling
• Local Java class: when the Java files are located in the content repository,
next to the Sightly template, only the class name is required to call the logic
• Bundle Java class: the Java class must be compiled and deployed within
an OSGi bundle (recommended when Java code implements logic
common to many components)
27
Sightly: the basics of the language
• Many ways to do the same thing. But, what kind of Use-API is better?
• Model logic:
This logic is not tied to a template and is potentially reusable among
components. It should aim to form a stable API that changes little, even in
case of a full redesign. ➔ Java located in OSGi bundle
Example: Java class retrieving information from a web service; Java class
implementing logic for computing the menu structure
• View logic:
This logic is specific to the templates and is likely to change if the design
changes. It is thus a good practice to locate it in the content repository, next
to the template.
➔ JavaScript located in component if components are to be maintained by front-end devs (typically
with Brackets).
➔ Java located in component if performance is critical (e.g. when many requests are not cached by
the dispatcher).
Example: code implementing logic to output certain css classes inside the
template mark up (e.g., list menu, with selected/non selected items)
28
Not a silver bullet
• Sightly is a good option to improve the maintanability of your AEM
components but…
• You should follow best practices and guidelines otherwise your template code can
explode easily
• data-sly-unwrap can be evil
• wrap author/preview version of HTML inside smaller templates to be included; this makes your
components easier to read
• avoid use context=‘‘unsafe’’
• It is not extensible with new block statements or options
• Can be hard to debug
• <img data-sly-use.logic=‘‘foo.test.SomeLogic’’ data-sly-test=‘‘${logic.value}’’ >
• if the test is false, everything below img tag won’t be output; this can be hard to debug
• always use self closed elements
• Can lead to many Use API files containing the same logic
• Before implementing a new one, think about a common class extending WCMUse or Sling Model
• Can be frustrating, sometimes
• Write Use API external code even for the easy tasks
• Follow a style guide: https://github.com/Netcentric/aem-sightly-style-guide
29
Sightly and Sling Models: an amazing combination
• Sling Models are POJOs implementing the adapter pattern. They can be
automatically mapped from Sling objects
• Resource
• SlingHttpRequest
• Entirely annotation driven
• OOTB, support resource properties (implemented with ValueMap), SlingBindings,
OSGi services, request attributes
• Current latest version: 1.2.0
• AEM6+SP2 comes with 1.0.0
• Versions > 1.0.0 contain very useful features:
• 1.0.6: injector-specific annotations
• 1.1.0: @Self, @SlingObject, @ResourcePath annotations
• 1.2.0: Sling validation
30
Sightly and Sling Models: basic usage
package com.foo.core;
@Model(adaptables=Resource.class)
public class MyModel {
@Inject private String propertyName;
public String getResult() {
return ‘‘Hello World ’’ + propertyName;
}
}
• Class is annotated with @Model
• adaptbles option defines which types of objects are adaptable to this Sling Model
• Fields that need to be injected are annotated
In this case, propertyName is a property coming from the adapted resource
• Constructor injection (since 1.1.0)
@Model(adaptables=Resource.class)
public class MyModel {
@Inject
public MyModel(@Named("propertyName") String propertyName) {
// constructor code
}
}
31
Sightly and Sling Models: basic usage
@Injected fields/methods are assumed to be required. To mark them as optional,
use @Optional:
@Model(adaptables=Resource.class)
public class MyModel {
@Inject @Optional
private String otherName;
}
A default value can be provided (for Strings & primitives):
@Model(adaptables=Resource.class)
public class MyModel {
@Inject @Default(values="defaultValue")
private String name;
}
32
Sightly and Sling Models: basic usage
OSGi services can be injected:
@Model(adaptables=Resource.class)
public class MyModel {
@Inject
private ResourceResolverFactory resourceResolverFactory;
}
List injection for child resources works by injecting grand child resources (since
Sling Models Impl 1.0.6). For example, the class
@Model(adaptables=Resource.class)
public class MyModel {
@Inject
private List<Resource> addresses;
}
addresses will contain address1 and address2
33
Sightly and Sling Models: basic usage
The @PostConstruct annotation can be used to add methods which are invoked upon
completion of all injections:
@Model(adaptables=SlingHttpServletRequest.class)
public class MyModel {
@Inject
private PrintWriter out;
@Inject
@Named("log")
private Logger logger;
@PostConstruct
protected void sayHello() {
logger.info("hello");
}
}
34
Sightly and Sling Models: basic usage
Available injectors:
https://sling.apache.org/documentation/bundles/models.html#available-injectors
35
Sightly and Sling Models: basic usage
Injector-specific annotation vs normal annotations
Those annotations replace @Via, @Filter, @Named, @Optional, @Required, @Source and
@Inject. @Default may still be used in addition to the injector-specific annotation to set
default values. All elements given above are optional.
Annotation
Supported Optional
Elements
Injector
@ScriptVariable optional and name script-bindings
@ValueMapValue optional, name and via valuemap
@ChildResource optional, name and via child-resources
@RequestAttribute optional, name and via request-attributes
@ResourcePath optional, path, and name resource-path
@OSGiService optional, filter osgi-services
@Self optional self
@SlingObject optional sling-object
36
Sightly and Sling Models: client code
From a Sightly template:
<div data-sly-use.model=‘‘com.foo.core.MyModel’’>${model.result}</div>
From Java code:
MyModel model = resource.adaptTo(MyModel.class)
37
Sightly and Sling Models: learning from experience
• Sling Models are instantiated everytime they are used with data-sly-use or adaptTo.
Issues can happen when the Sling Model instantiation includes connection to DB or web
service calls. Best practice: put Sling Model instance inside request object (in case the
same model is used within the same request).
• They can be hard to debug sometimes…
Since Sling Models 1.2.0 there is another way of instantiating models. The OSGi service
ModelFactory provides a method for instantiating a model that throws exceptions. This is
not allowed by the Javadoc contract of the adaptTo method. That way null checks are not
necessary and it is easier to see why instantiation of the model failed.
• Why Sling Models and NOT WCMUse
Sling Models are based on the adapter pattern
Dependency injection
Less simpler code
It’s a POJPO  unit testable
38
Sightly and Sling Models: ACS AEM commons and wcm.io
https://adobe-consulting-services.github.io/acs-aem-commons/features/aem-sling-models-
injectors.html
Allows for Sling Models classes and interfaces to be injected with common AEM-related
objects, namely those made available using <cq:defineObjects/>: resource,
resourceResolver, componentContext, pageManager, etc.
@Inject
private Page resourcePage;
http://wcm.io/sling/models/
Support injection request-derived context objects on all models, not only when the adaptable
is a request
39
• https://github.com/Adobe-Marketing-Cloud/aem-sightly-sample-todomvc/
Sightly TodoMVC Example
• https://github.com/Adobe-Marketing-Cloud/aem-sightly-repl
AEM Sightly Read–Eval–Print Loop
Useful links
40
• AEM 6 Project Archetype version 10
https://github.com/Adobe-Marketing-Cloud/aem-project-archetype
• AEM 6 Project bootstrap inside Eclipse + AEM Developer Tools for
Eclipse
http://docs.adobe.com/content/docs/en/dev-tools/aem-eclipse.html
1. Project overview
2. Automatic synch: FS  repo (both content package and bundle)
3. On demand synch: repo  FS
4. Change properties from Eclipse and automatic synch FS  repo
• Brackets
1. Syntax highlighting, auto completion (data-sly-* and variables used inside expression within
data attributes)
2. Automatic synch: FS  repo
3. On demand synch
• Archetype findings…
A few hands-on examples
Thanks
Stefano Celentano
s.celentano@reply.it

Contenu connexe

Tendances

Sling models by Justin Edelson
Sling models by Justin Edelson Sling models by Justin Edelson
Sling models by Justin Edelson AEM HUB
 
Adobe Experience Manager Core Components
Adobe Experience Manager Core ComponentsAdobe Experience Manager Core Components
Adobe Experience Manager Core ComponentsGabriel Walt
 
JCR, Sling or AEM? Which API should I use and when?
JCR, Sling or AEM? Which API should I use and when?JCR, Sling or AEM? Which API should I use and when?
JCR, Sling or AEM? Which API should I use and when?connectwebex
 
Introduction to HTML5
Introduction to HTML5Introduction to HTML5
Introduction to HTML5IT Geeks
 
Introduction to Sightly
Introduction to SightlyIntroduction to Sightly
Introduction to SightlyAnkit Gubrani
 
Heap Dump Analysis - AEM: Real World Issues
Heap Dump Analysis - AEM: Real World IssuesHeap Dump Analysis - AEM: Real World Issues
Heap Dump Analysis - AEM: Real World IssuesKanika Gera
 
Basics of Solr and Solr Integration with AEM6
Basics of Solr and Solr Integration with AEM6Basics of Solr and Solr Integration with AEM6
Basics of Solr and Solr Integration with AEM6DEEPAK KHETAWAT
 
Understanding Sling Models in AEM
Understanding Sling Models in AEMUnderstanding Sling Models in AEM
Understanding Sling Models in AEMAccunity Software
 
An Introduction to the DOM
An Introduction to the DOMAn Introduction to the DOM
An Introduction to the DOMMindy McAdams
 
JavaScript - Chapter 8 - Objects
 JavaScript - Chapter 8 - Objects JavaScript - Chapter 8 - Objects
JavaScript - Chapter 8 - ObjectsWebStackAcademy
 
Angular Introduction By Surekha Gadkari
Angular Introduction By Surekha GadkariAngular Introduction By Surekha Gadkari
Angular Introduction By Surekha GadkariSurekha Gadkari
 
The six key steps to AEM architecture
The six key steps to AEM architectureThe six key steps to AEM architecture
The six key steps to AEM architectureAshokkumar T A
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to JavascriptAmit Tyagi
 

Tendances (20)

Osgi
OsgiOsgi
Osgi
 
Sling models by Justin Edelson
Sling models by Justin Edelson Sling models by Justin Edelson
Sling models by Justin Edelson
 
Adobe Experience Manager Core Components
Adobe Experience Manager Core ComponentsAdobe Experience Manager Core Components
Adobe Experience Manager Core Components
 
slingmodels
slingmodelsslingmodels
slingmodels
 
JCR, Sling or AEM? Which API should I use and when?
JCR, Sling or AEM? Which API should I use and when?JCR, Sling or AEM? Which API should I use and when?
JCR, Sling or AEM? Which API should I use and when?
 
Introduction to HTML5
Introduction to HTML5Introduction to HTML5
Introduction to HTML5
 
Sling Models Overview
Sling Models OverviewSling Models Overview
Sling Models Overview
 
Introduction to Sightly
Introduction to SightlyIntroduction to Sightly
Introduction to Sightly
 
Heap Dump Analysis - AEM: Real World Issues
Heap Dump Analysis - AEM: Real World IssuesHeap Dump Analysis - AEM: Real World Issues
Heap Dump Analysis - AEM: Real World Issues
 
Basics of Solr and Solr Integration with AEM6
Basics of Solr and Solr Integration with AEM6Basics of Solr and Solr Integration with AEM6
Basics of Solr and Solr Integration with AEM6
 
Understanding Sling Models in AEM
Understanding Sling Models in AEMUnderstanding Sling Models in AEM
Understanding Sling Models in AEM
 
Aem Training Tutorials for Beginners
Aem  Training Tutorials for BeginnersAem  Training Tutorials for Beginners
Aem Training Tutorials for Beginners
 
CSS
CSSCSS
CSS
 
An Introduction to the DOM
An Introduction to the DOMAn Introduction to the DOM
An Introduction to the DOM
 
JavaScript - Chapter 8 - Objects
 JavaScript - Chapter 8 - Objects JavaScript - Chapter 8 - Objects
JavaScript - Chapter 8 - Objects
 
Angular Introduction By Surekha Gadkari
Angular Introduction By Surekha GadkariAngular Introduction By Surekha Gadkari
Angular Introduction By Surekha Gadkari
 
The six key steps to AEM architecture
The six key steps to AEM architectureThe six key steps to AEM architecture
The six key steps to AEM architecture
 
Basic-CSS-tutorial
Basic-CSS-tutorialBasic-CSS-tutorial
Basic-CSS-tutorial
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
Css Ppt
Css PptCss Ppt
Css Ppt
 

Similaire à Introduction to Sightly and Sling Models

Advanced Site Studio Class, June 18, 2012
Advanced Site Studio Class, June 18, 2012Advanced Site Studio Class, June 18, 2012
Advanced Site Studio Class, June 18, 2012Lee Klement
 
ASP.NET MVC 5 - EF 6 - VS2015
ASP.NET MVC 5 - EF 6 - VS2015ASP.NET MVC 5 - EF 6 - VS2015
ASP.NET MVC 5 - EF 6 - VS2015Hossein Zahed
 
Add-On Development: EE Expects that Every Developer will do his Duty
Add-On Development: EE Expects that Every Developer will do his DutyAdd-On Development: EE Expects that Every Developer will do his Duty
Add-On Development: EE Expects that Every Developer will do his Dutyreedmaniac
 
Handlebars and Require.js
Handlebars and Require.jsHandlebars and Require.js
Handlebars and Require.jsIvano Malavolta
 
AngularJS 1.x - your first application (problems and solutions)
AngularJS 1.x - your first application (problems and solutions)AngularJS 1.x - your first application (problems and solutions)
AngularJS 1.x - your first application (problems and solutions)Igor Talevski
 
When Sightly Meets Slice by Tomasz Niedźwiedź
When Sightly Meets Slice by Tomasz NiedźwiedźWhen Sightly Meets Slice by Tomasz Niedźwiedź
When Sightly Meets Slice by Tomasz NiedźwiedźAEM HUB
 
Add-On Development: EE Expects that Every Developer will do his Duty
Add-On Development: EE Expects that Every Developer will do his DutyAdd-On Development: EE Expects that Every Developer will do his Duty
Add-On Development: EE Expects that Every Developer will do his DutyLeslie Doherty
 
Improving the Quality of Existing Software - DevIntersection April 2016
Improving the Quality of Existing Software - DevIntersection April 2016Improving the Quality of Existing Software - DevIntersection April 2016
Improving the Quality of Existing Software - DevIntersection April 2016Steven Smith
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing SoftwareSteven Smith
 
O365Con18 - Using ARM Templates to Deploy Solutions on Azure - Kevin Timmermann
O365Con18 - Using ARM Templates to Deploy Solutions on Azure - Kevin TimmermannO365Con18 - Using ARM Templates to Deploy Solutions on Azure - Kevin Timmermann
O365Con18 - Using ARM Templates to Deploy Solutions on Azure - Kevin TimmermannNCCOMMS
 
Session 34 - JDBC Best Practices, Introduction to Design Patterns
Session 34 - JDBC Best Practices, Introduction to Design PatternsSession 34 - JDBC Best Practices, Introduction to Design Patterns
Session 34 - JDBC Best Practices, Introduction to Design PatternsPawanMM
 
Node.js and the MySQL Document Store
Node.js and the MySQL Document StoreNode.js and the MySQL Document Store
Node.js and the MySQL Document StoreRui Quelhas
 
2008_478_Lyons_ppt.ppt
2008_478_Lyons_ppt.ppt2008_478_Lyons_ppt.ppt
2008_478_Lyons_ppt.pptChadharris42
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing SoftwareSteven Smith
 

Similaire à Introduction to Sightly and Sling Models (20)

Dust.js
Dust.jsDust.js
Dust.js
 
Html,CSS & UI/UX design
Html,CSS & UI/UX designHtml,CSS & UI/UX design
Html,CSS & UI/UX design
 
Advanced Site Studio Class, June 18, 2012
Advanced Site Studio Class, June 18, 2012Advanced Site Studio Class, June 18, 2012
Advanced Site Studio Class, June 18, 2012
 
ASP.NET MVC 5 - EF 6 - VS2015
ASP.NET MVC 5 - EF 6 - VS2015ASP.NET MVC 5 - EF 6 - VS2015
ASP.NET MVC 5 - EF 6 - VS2015
 
Add-On Development: EE Expects that Every Developer will do his Duty
Add-On Development: EE Expects that Every Developer will do his DutyAdd-On Development: EE Expects that Every Developer will do his Duty
Add-On Development: EE Expects that Every Developer will do his Duty
 
presentation
presentationpresentation
presentation
 
Handlebars and Require.js
Handlebars and Require.jsHandlebars and Require.js
Handlebars and Require.js
 
AngularJS 1.x - your first application (problems and solutions)
AngularJS 1.x - your first application (problems and solutions)AngularJS 1.x - your first application (problems and solutions)
AngularJS 1.x - your first application (problems and solutions)
 
When Sightly Meets Slice by Tomasz Niedźwiedź
When Sightly Meets Slice by Tomasz NiedźwiedźWhen Sightly Meets Slice by Tomasz Niedźwiedź
When Sightly Meets Slice by Tomasz Niedźwiedź
 
Add-On Development: EE Expects that Every Developer will do his Duty
Add-On Development: EE Expects that Every Developer will do his DutyAdd-On Development: EE Expects that Every Developer will do his Duty
Add-On Development: EE Expects that Every Developer will do his Duty
 
presentation
presentationpresentation
presentation
 
Handlebars & Require JS
Handlebars  & Require JSHandlebars  & Require JS
Handlebars & Require JS
 
Improving the Quality of Existing Software - DevIntersection April 2016
Improving the Quality of Existing Software - DevIntersection April 2016Improving the Quality of Existing Software - DevIntersection April 2016
Improving the Quality of Existing Software - DevIntersection April 2016
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing Software
 
O365Con18 - Using ARM Templates to Deploy Solutions on Azure - Kevin Timmermann
O365Con18 - Using ARM Templates to Deploy Solutions on Azure - Kevin TimmermannO365Con18 - Using ARM Templates to Deploy Solutions on Azure - Kevin Timmermann
O365Con18 - Using ARM Templates to Deploy Solutions on Azure - Kevin Timmermann
 
Session 34 - JDBC Best Practices, Introduction to Design Patterns
Session 34 - JDBC Best Practices, Introduction to Design PatternsSession 34 - JDBC Best Practices, Introduction to Design Patterns
Session 34 - JDBC Best Practices, Introduction to Design Patterns
 
Introduction to AngularJs
Introduction to AngularJsIntroduction to AngularJs
Introduction to AngularJs
 
Node.js and the MySQL Document Store
Node.js and the MySQL Document StoreNode.js and the MySQL Document Store
Node.js and the MySQL Document Store
 
2008_478_Lyons_ppt.ppt
2008_478_Lyons_ppt.ppt2008_478_Lyons_ppt.ppt
2008_478_Lyons_ppt.ppt
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing Software
 

Dernier

CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 

Dernier (20)

CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 

Introduction to Sightly and Sling Models

  • 1. Introduction to Sightly and Sling Models in AEM6 Stefano Celentano
  • 2. 2 • What is Sightly? • Why Sightly? • Separation of concerns • Comparing JSP and Sightly development • Sightly features • Sightly: the basics of the language • Not a silver bullet • Sightly and Sling Models • An amazing combination • Basic usage • Learning from experience • wcm-io and ACS Commons libraries • Useful links • A few hands-on examples Summary
  • 3. 3 • New secure server-side HTML Templating Language introduced with AEM6 for efficient development • “Sightly” (meaning “pleasing to the eye”) • “Alternative” to JSP • Specification and TCK open sourced to GitHub • Reference Adobe implementation donated to Apache Sling by Adobe (September 2014) • Sightly reference implementation has been folded into Apache Sling project • org.apache.sling.scripting.sightly • org.apache.sling.xss What is Sightly
  • 6. 6 The standard workflow: • Front end developers create HTML mark up, designs with all necessary client side libraries • (AEM) back end developers take this well formed, high-fidelity static HTML “prototype” • Systematically split the whole template in pieces • Put it together again as JSP templates and components • Add custom business logic inside JSP templates and components This leads to well known issues: • The process of splitting and putting together is error prone • The process itself is time consuming • This way of development does not provide good (and simple) separation of concerns between UI and business logic • As front end developers can’t easily maintain JSPs, they don’t develop new components “inside” AEM • They don’t directly cope with components issues in Author mode (both visualization and UI issues) Why Sightly: separation of concerns
  • 9. 9 Why Sightly: comparing JSP and Sightly
  • 10. 10 Why Sightly: comparing JSP and Sightly
  • 11. 11 Why Sightly: comparing JSP and Sightly
  • 12. 12 Why Sightly: comparing JSP and Sightly
  • 13. 13 Why Sightly: comparing JSP and Sightly • Writing custom tag lib is not easy • Need to mantain both Java class and TLD • Custom tag lib lifecycle is hard to understand and difficult to integrate inside the templates • Have you ever effectively used it for your projects? JSP Sightly Based on Published Standards / Open Source?Y (*) N Y IDE Support? Y Y/N Officially Documented / Supported? Y Y Documented Extension Model? Y N Includes XSS escaping? Y (**) Y Allows Basic Logic? Y Y Enables Bad Coding Practices? Y N * Some proprietary TagLibs used for interacting with CQ ** Provided by additional tag libraries
  • 14. 14 Why Sightly: features • Code-less language, forcing strict separation of concerns • Powerful extension points with the Use-API • Automatic contextual HTML escaping and XSS protection • Automatically removes HTML attributes if value is empty • Reuses HTML blocks for statements
  • 15. 15 Sightly: the basics of the language Expression language example: <a href=‘‘{properties.link || ‘#’}’’ title=‘‘{properties.jcr:title}’’> ${properties.jcr:description} </a> Features: - Automatic contextual HTML escaping and XSS escaping (warning!) - Fallback value if property is empty - Remove HTML attribute if value is empty
  • 16. 16 Sightly: the basics of the language • Sightly comments <!-- /* This will disappear from the output *--> • Expression language ${properties.myProperty} • They can only be used in attribute values, comments or in element content • Standard bindings are available as in JSPs • Block statements <div data-sly-include=‘‘another-template.html’’></div>
  • 17. 17 Sightly: the basics of the language • Expression bindings: • ${properties} • ${pageProperties} • ${inheritedPageProperties} • ${request} Sling Request • ${resource} Sling Resource • ${currentPage} WCM Page • ${currentDesign} WCM Design • ${component} WCM Component • ${wcmmode} WCM Mode Access properties with dot notation ${properties.foo} To avoid complex expressions inside templates, Sightly does not allow passing arguments to function call. Only zero argument calls are allowed from templates.
  • 18. 18 Sightly: the basics of the language • Options allow to manipulate the result of an expression, or to pass arguments to block statements • Everything after the @ are comma separated options: ${myVar @ optionOne, optionTwo} • Examples: • String formatting: ${‘Page {0} of {1}’ @ format=[current, total]} • Internationalization: ${‘Page’ @ i18n} • Array join: ${[‘one’, ‘two’] @ join=‘; ’}
  • 19. 19 Sightly: the basics of the language • Display context • Every expression in Sightly has a display context • Display context depends on the location within the HTML structure • Example: text node, attribute, … • Sightly automatically detect the context of expressions and escape them appropriately (to prevent XSS) This is not true for script (JS) and style (CSS) contexts In this case we should explicitly set the context • Example <a href="${properties.link}" title="${properties.title}">${properties.text}</a> Three variables, three different contexts. No explicit context setting is required in the above cases
  • 20. 20 Sightly: the basics of the language • Display context option • The context option offers control over escaping and XSS protection • Explicit context must be set for style contexts: <span style="color: ${properties.color @ context='styleToken'};">...</span> • To safely output markup (filtering out scripts) <div>${properties.richText @ context=‘html’}</div> uses AntiSamy policy rules The default antisamy configuration is present at /libs/cq/xssprotection/config.xml, which can be overlaid with your custom config within /apps. • Adding URI validation protection to other attributes than src or href <p data-link=‘‘${link @ context=‘uri’}’’>text</p>
  • 21. 21 Sightly: the basics of the language • Most useful contexts and what they do: • uri To display links and paths (validates URI) • attribute Encodes HTML special characters • text Encodes HTML special characters • scriptString Encodes characters that would break out the string • styleString Validates CSS tokens. Outputs nothing if it fails • html Filters HTML to meet AntiSamy policy rules, removing what doesn’t match • unsafe Disable all escaping and XSS protections
  • 22. 22 Sightly: the basics of the language • Block statements • To keep markup valid, block statements are defined by data-sly-* attributes that can be added to any element on the markup • <input data-sly-STATEMENT=‘‘foo’’ /> • Block statements can have no value, a static value, or an expression <input data-sly-STATEMENT=‘‘${bar}’’ /> • Despite using data-attributes, block statements are all executed on the server and no data-sly-* attribute is sent to the client! • Sightly block statements: • Markup inclusion: Include, Resource • Control flow: test, list, template, call • Markup modification: unwrap, element, attribute, text • Object initialization: use
  • 23. 23 Sightly: the basics of the language • Template and call statements • Similar to data-sly-include • Main difference: you can pass parameters to the included template • Templates must be declared and called from another template • <data-sly-template> declares a template <template data-sly-template.header> <div> my template </div> </template> Defines a template called header Notice: the host element are not output by Sightly. If you call this template the only printed mark up will be <div> my template </div> • <div data-sly-call=‘‘header’’></div> calls the template header defined above • Templates can be located in a different file • Templates accept parameters <template data-sly-template.two=‘‘${ @ title}’’> <h1>${title}</h1> </template> <div data-sly-call=‘‘${two @ title=properties.jcr:title}’’></div>
  • 24. 24 Sightly: the basics of the language • Unwrap statement • Removes the host element while retaining its content <div data-sly-unwrap> <h1> Title </h1> </div> Output: <h1> Title </h1> • Warning! • Use unwrap only when there’s no other way to write your template • Prefer adding statements to existing elements • Templates can easily become difficult to read • Unwrap can also be subject to condition <div class=‘‘edit-md’’ data-sly-unwrap=‘‘${wcmmode.edit}’’> Text </div> Output: Text in EDIT mode Output in PREVIEW/PUBLISH mode: <div class=‘‘edit-md’’> Text </div> • Use data-sly-test to remove the element content as well
  • 25. 25 Sightly: the basics of the language • Use statement: Sightly Javascript Use API. Enables a Sightly file to access helper code written in Javascript. • Initialize a helper objects <div data-sly-use.logic=‘‘logic.js’’>${logic.value}</div> Inside logic.js file use(function()) { return { value: ‘‘Hello World’’ }; }); Output: <div> Hello World </div> • Use Javascript Use API only for very simple tasks (date formatting, text formatting, simple conditional logic, …): • Javascript Use API is server-side Javascript (some JS native features are not fully supported) • Cannot be debugged • Very hard to find errors • It’s slow • Very hard to write Javascript Use API code for more complex task (e.g., cycling on repository nodes, calling external services, etc.)
  • 26. 26 Sightly: the basics of the language • Use statement: Sightly Java Use API enables a Sightly file to access helper methods in a custom Java class. • POJO extending WCMUse class • WCMUse has been deprecated from AEM 6.1 and replaced with WCMUsePojo which uses the new Sightly API from Apache Sling • Local Java class: when the Java files are located in the content repository, next to the Sightly template, only the class name is required to call the logic • Bundle Java class: the Java class must be compiled and deployed within an OSGi bundle (recommended when Java code implements logic common to many components)
  • 27. 27 Sightly: the basics of the language • Many ways to do the same thing. But, what kind of Use-API is better? • Model logic: This logic is not tied to a template and is potentially reusable among components. It should aim to form a stable API that changes little, even in case of a full redesign. ➔ Java located in OSGi bundle Example: Java class retrieving information from a web service; Java class implementing logic for computing the menu structure • View logic: This logic is specific to the templates and is likely to change if the design changes. It is thus a good practice to locate it in the content repository, next to the template. ➔ JavaScript located in component if components are to be maintained by front-end devs (typically with Brackets). ➔ Java located in component if performance is critical (e.g. when many requests are not cached by the dispatcher). Example: code implementing logic to output certain css classes inside the template mark up (e.g., list menu, with selected/non selected items)
  • 28. 28 Not a silver bullet • Sightly is a good option to improve the maintanability of your AEM components but… • You should follow best practices and guidelines otherwise your template code can explode easily • data-sly-unwrap can be evil • wrap author/preview version of HTML inside smaller templates to be included; this makes your components easier to read • avoid use context=‘‘unsafe’’ • It is not extensible with new block statements or options • Can be hard to debug • <img data-sly-use.logic=‘‘foo.test.SomeLogic’’ data-sly-test=‘‘${logic.value}’’ > • if the test is false, everything below img tag won’t be output; this can be hard to debug • always use self closed elements • Can lead to many Use API files containing the same logic • Before implementing a new one, think about a common class extending WCMUse or Sling Model • Can be frustrating, sometimes • Write Use API external code even for the easy tasks • Follow a style guide: https://github.com/Netcentric/aem-sightly-style-guide
  • 29. 29 Sightly and Sling Models: an amazing combination • Sling Models are POJOs implementing the adapter pattern. They can be automatically mapped from Sling objects • Resource • SlingHttpRequest • Entirely annotation driven • OOTB, support resource properties (implemented with ValueMap), SlingBindings, OSGi services, request attributes • Current latest version: 1.2.0 • AEM6+SP2 comes with 1.0.0 • Versions > 1.0.0 contain very useful features: • 1.0.6: injector-specific annotations • 1.1.0: @Self, @SlingObject, @ResourcePath annotations • 1.2.0: Sling validation
  • 30. 30 Sightly and Sling Models: basic usage package com.foo.core; @Model(adaptables=Resource.class) public class MyModel { @Inject private String propertyName; public String getResult() { return ‘‘Hello World ’’ + propertyName; } } • Class is annotated with @Model • adaptbles option defines which types of objects are adaptable to this Sling Model • Fields that need to be injected are annotated In this case, propertyName is a property coming from the adapted resource • Constructor injection (since 1.1.0) @Model(adaptables=Resource.class) public class MyModel { @Inject public MyModel(@Named("propertyName") String propertyName) { // constructor code } }
  • 31. 31 Sightly and Sling Models: basic usage @Injected fields/methods are assumed to be required. To mark them as optional, use @Optional: @Model(adaptables=Resource.class) public class MyModel { @Inject @Optional private String otherName; } A default value can be provided (for Strings & primitives): @Model(adaptables=Resource.class) public class MyModel { @Inject @Default(values="defaultValue") private String name; }
  • 32. 32 Sightly and Sling Models: basic usage OSGi services can be injected: @Model(adaptables=Resource.class) public class MyModel { @Inject private ResourceResolverFactory resourceResolverFactory; } List injection for child resources works by injecting grand child resources (since Sling Models Impl 1.0.6). For example, the class @Model(adaptables=Resource.class) public class MyModel { @Inject private List<Resource> addresses; } addresses will contain address1 and address2
  • 33. 33 Sightly and Sling Models: basic usage The @PostConstruct annotation can be used to add methods which are invoked upon completion of all injections: @Model(adaptables=SlingHttpServletRequest.class) public class MyModel { @Inject private PrintWriter out; @Inject @Named("log") private Logger logger; @PostConstruct protected void sayHello() { logger.info("hello"); } }
  • 34. 34 Sightly and Sling Models: basic usage Available injectors: https://sling.apache.org/documentation/bundles/models.html#available-injectors
  • 35. 35 Sightly and Sling Models: basic usage Injector-specific annotation vs normal annotations Those annotations replace @Via, @Filter, @Named, @Optional, @Required, @Source and @Inject. @Default may still be used in addition to the injector-specific annotation to set default values. All elements given above are optional. Annotation Supported Optional Elements Injector @ScriptVariable optional and name script-bindings @ValueMapValue optional, name and via valuemap @ChildResource optional, name and via child-resources @RequestAttribute optional, name and via request-attributes @ResourcePath optional, path, and name resource-path @OSGiService optional, filter osgi-services @Self optional self @SlingObject optional sling-object
  • 36. 36 Sightly and Sling Models: client code From a Sightly template: <div data-sly-use.model=‘‘com.foo.core.MyModel’’>${model.result}</div> From Java code: MyModel model = resource.adaptTo(MyModel.class)
  • 37. 37 Sightly and Sling Models: learning from experience • Sling Models are instantiated everytime they are used with data-sly-use or adaptTo. Issues can happen when the Sling Model instantiation includes connection to DB or web service calls. Best practice: put Sling Model instance inside request object (in case the same model is used within the same request). • They can be hard to debug sometimes… Since Sling Models 1.2.0 there is another way of instantiating models. The OSGi service ModelFactory provides a method for instantiating a model that throws exceptions. This is not allowed by the Javadoc contract of the adaptTo method. That way null checks are not necessary and it is easier to see why instantiation of the model failed. • Why Sling Models and NOT WCMUse Sling Models are based on the adapter pattern Dependency injection Less simpler code It’s a POJPO  unit testable
  • 38. 38 Sightly and Sling Models: ACS AEM commons and wcm.io https://adobe-consulting-services.github.io/acs-aem-commons/features/aem-sling-models- injectors.html Allows for Sling Models classes and interfaces to be injected with common AEM-related objects, namely those made available using <cq:defineObjects/>: resource, resourceResolver, componentContext, pageManager, etc. @Inject private Page resourcePage; http://wcm.io/sling/models/ Support injection request-derived context objects on all models, not only when the adaptable is a request
  • 39. 39 • https://github.com/Adobe-Marketing-Cloud/aem-sightly-sample-todomvc/ Sightly TodoMVC Example • https://github.com/Adobe-Marketing-Cloud/aem-sightly-repl AEM Sightly Read–Eval–Print Loop Useful links
  • 40. 40 • AEM 6 Project Archetype version 10 https://github.com/Adobe-Marketing-Cloud/aem-project-archetype • AEM 6 Project bootstrap inside Eclipse + AEM Developer Tools for Eclipse http://docs.adobe.com/content/docs/en/dev-tools/aem-eclipse.html 1. Project overview 2. Automatic synch: FS  repo (both content package and bundle) 3. On demand synch: repo  FS 4. Change properties from Eclipse and automatic synch FS  repo • Brackets 1. Syntax highlighting, auto completion (data-sly-* and variables used inside expression within data attributes) 2. Automatic synch: FS  repo 3. On demand synch • Archetype findings… A few hands-on examples

Notes de l'éditeur

  1. The name “Sightly” (meaning “pleasing to the eye”) highlights its focus on keeping your markup beautiful, and thus maintainable, once made dynamic.
  2. This way of development does not provide good (and simple) separation of concerns between UI and business logic: in realtà I modi ci sarebbero: CUSTOM TAG LIBRARIES
  3. Il tempo per lo sviluppo dei component con l’utilizzo di JSP + logica Java all’interno è maggiore
  4. AUTOMATIC CONTEXTUAL HTML ESCAPING AND XSS PROTECTION: Sightly automatically filters and escapes all variables being output to the presentation layer to prevent cross-site-scripting (XSS) vulnerabilities. As Sightly understands the HTML syntax, it is capable to automatically detect the scope in which variables are placed, and automatically do proper context-aware escaping and XSS protection. Yet, it is possible to manually control the display context if needed. REUSES HTML BLOCKS FOR STATEMENTS: Sightly block statements are custom data attributes added directly to existing HTML. This allows easy and unobtrusive annotation of a prototype static HTML page, converting it to a functioning dynamic template without breaking the validity of the HTML code.
  5. The display context of a Sightly expression refers to its location within the structure of the HTML page. For example, if the expression appears in place that would produce a text node once rendered, then it is said to be in a text context. If it is found within the value of an attribute, then it is said to be in an attribute context, and so forth. With the exception of script (JS) and style (CSS) contexts, Sightly will automatically detect the context of expressions and escape them appropriately, to prevent XSS security problems. In the case of scripts and CSS, the desired context behavior must be explicitly set. Additionally, the context behavior can also be explicitly set in any other case where an override of the automatic behavior is desired. Here we have three variables in three different contexts: properties.link (uri context), properties.title (attribute context) and properties.text (text context). Sightly will escape each of these differently in accordance with the security requirements of their respective contexts. No explicit context setting is required in normal cases such as this one: <a href="${properties.link}" title="${properties.title}">${properties.text}</a>
  6. The display context of a Sightly expression refers to its location within the structure of the HTML page. For example, if the expression appears in place that would produce a text node once rendered, then it is said to be in a text context. If it is found within the value of an attribute, then it is said to be in an attribute context, and so forth. With the exception of script (JS) and style (CSS) contexts, Sightly will automatically detect the context of expressions and escape them appropriately, to prevent XSS security problems. In the case of scripts and CSS, the desired context behavior must be explicitly set. Additionally, the context behavior can also be explicitly set in any other case where an override of the automatic behavior is desired. Here we have three variables in three different contexts: properties.link (uri context), properties.title (attribute context) and properties.text (text context). Sightly will escape each of these differently in accordance with the security requirements of their respective contexts. No explicit context setting is required in normal cases such as this one: <a href="${properties.link}" title="${properties.title}">${properties.text}</a>
  7. Less code to write (only one annotation is necessary in most of the cases) More robust (in case of name collisions among the different injectors, you make sure that the right injector is used) Better IDE support (because the annotations provide elements for each configuration which is available for that specific injector, i.e. filter only for OSGi services)
  8. Why Sling Models and NOT WCMUse: https://www.cognifide.com/blogs/cq/sightly-and-slice---where-a-beautiful-markup-meets-a-beautiful-code/#.VgK7-d_tmko
  9. Why Sling Models and NOT WCMUse: https://www.cognifide.com/blogs/cq/sightly-and-slice---where-a-beautiful-markup-meets-a-beautiful-code/#.VgK7-d_tmko