incubator-sling-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From conflue...@apache.org
Subject [CONF] Apache Sling > Scripting variables
Date Thu, 29 Jul 2010 13:01:00 GMT
<html>
<head>
    <base href="https://cwiki.apache.org/confluence">
            <link rel="stylesheet" href="/confluence/s/1810/9/1/_/styles/combined.css?spaceKey=SLING&amp;forWysiwyg=true"
type="text/css">
    </head>
<body style="background: white;" bgcolor="white" class="email-body">
<div id="pageContent">
<div id="notificationFormat">
<div class="wiki-content">
<div class="email">
    <h2><a href="https://cwiki.apache.org/confluence/display/SLING/Scripting+variables">Scripting
variables</a></h2>
    <h4>Page <b>edited</b> by             <a href="https://cwiki.apache.org/confluence/display/~alexander.klimetschek@googlemail.com">Alexander
Klimetschek</a>
    </h4>
        <br/>
                         <h4>Changes (1)</h4>
                                 
    
<div id="page-diffs">
            <table class="diff" cellpadding="0" cellspacing="0">
            <tr><td class="diff-snipped" >...<br></td></tr>
            <tr><td class="diff-unchanged" >{code} <br> <br></td></tr>
            <tr><td class="diff-changed-lines" >For more options of the sling
taglib see the [tag lib definition <span class="diff-changed-words">file|http://svn.apache.org/viewvc/sling/trunk/bundles/scripting/jsp-taglib/src/main/resources/META-INF/taglib<span
class="diff-added-chars"style="background-color: #dfd;">11</span>.tld?view=markup].</span>
<br></td></tr>
            <tr><td class="diff-unchanged" > <br>h2. ESP <br></td></tr>
            <tr><td class="diff-snipped" >...<br></td></tr>
        </table>
</div>                            <h4>Full Content</h4>
                    <div class="notificationGreySide">
        <h2><a name="Scriptingvariables-Commonscriptingvariables"></a>Common
scripting variables</h2>

<p>The basic objects, such as the request and response, are available for most scripting
languages (Note the differences for eg. JSP below).</p>

<div class='table-wrap'>
<table class='confluenceTable'><tbody>
<tr>
<th class='confluenceTh'>Name   </th>
<th class='confluenceTh'> Description </th>
</tr>
<tr>
<td class='confluenceTd'> request </td>
<td class='confluenceTd'> <a href="http://svn.apache.org/viewvc/sling/trunk/bundles/api/src/main/java/org/apache/sling/api/SlingHttpServletRequest.java?view=markup"
class="external-link" rel="nofollow">SlingHttpServletRequest</a> object, providing
access to the HTTP request header information - extends the standard <a href="http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/HttpServletRequest.html"
class="external-link" rel="nofollow">HttpServletRequest</a> - and provides access
to Sling-specific things like resource, path info, selector, etc. </td>
</tr>
<tr>
<td class='confluenceTd'> response </td>
<td class='confluenceTd'> <a href="http://svn.apache.org/viewvc/sling/trunk/bundles/api/src/main/java/org/apache/sling/api/SlingHttpServletResponse.java?view=markup"
class="external-link" rel="nofollow">SlingHttpServletResponse</a> object, providing
access for the HTTP response that is created by the server. This is currently the same as
the <a href="http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/HttpServletResponse.html"
class="external-link" rel="nofollow">HttpServletResponse</a> from which it extends.
</td>
</tr>
<tr>
<td class='confluenceTd'> sling </td>
<td class='confluenceTd'> <a href="http://svn.apache.org/viewvc/sling/trunk/bundles/api/src/main/java/org/apache/sling/api/scripting/SlingScriptHelper.java?view=markup"
class="external-link" rel="nofollow">SlingScriptHelper</a>, containing convenience
methods for scripts, mainly <tt>sling.include('/some/other/resource')</tt> for
including the responses of other resources inside this response (eg. embedding header html
snippets) and <tt>sling.getService(foo.bar.Service.class)</tt> to retrieve OSGi
services available in Sling (Class notation depending on scripting language). </td>
</tr>
<tr>
<td class='confluenceTd'> resource </td>
<td class='confluenceTd'> Current <a href="http://svn.apache.org/viewvc/sling/trunk/bundles/api/src/main/java/org/apache/sling/api/resource/Resource.java?view=markup"
class="external-link" rel="nofollow">Resource</a> to handle, depending on the URL
of the request. Same as <tt>request.getResource()</tt>. </td>
</tr>
<tr>
<td class='confluenceTd'> reader </td>
<td class='confluenceTd'> Direct access to the <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/io/Reader.html"
class="external-link" rel="nofollow">Reader</a> of the request - same as <tt>request.getReader()</tt>.
Use it for reading the data of an HTTP request body. </td>
</tr>
<tr>
<td class='confluenceTd'> out </td>
<td class='confluenceTd'> Direct access to the <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/io/PrintWriter.html"
class="external-link" rel="nofollow">PrintWriter</a> of the response - same as <tt>response.getWriter()</tt>.
Use it for writing to the HTTP response body. </td>
</tr>
<tr>
<td class='confluenceTd'> flush </td>
<td class='confluenceTd'> Indicates whether the output used by the script shall be flushed
after the script evaluation ended. It is a Boolean, so use <tt>TRUE</tt> for flushing
or <tt>FALSE</tt> for not flushing, which is the default value. The boolean value
notation depends on the scripting language. </td>
</tr>
<tr>
<td class='confluenceTd'> log </td>
<td class='confluenceTd'> Provides an <a href="http://www.slf4j.org/api/org/slf4j/Logger.html"
class="external-link" rel="nofollow">SLF4J Logger</a> for logging to the Sling log
system from within scripts, eg. <tt>log.info("Executing my script")</tt>.</td>
</tr>
</tbody></table>
</div>


<p>See also the api documentation of the <a href="http://svn.apache.org/viewvc/sling/trunk/bundles/api/src/main/java/org/apache/sling/api/scripting/SlingBindings.java?view=markup"
class="external-link" rel="nofollow">org.apache.sling.api.scripting.SlingBindings.java</a>
which defines the common scripting variables.</p>

<p>This list can be expanded by bundles. See <a href="/confluence/display/SLING/Adding+New+Scripting+Variables"
title="Adding New Scripting Variables">Adding New Scripting Variables</a> for information.</p>

<p>In addition currently the <tt>currentNode</tt> binding is supported by
most scripting languages. If the current <tt>resource</tt> points to a JCR node
(which is typically the case in Sling), this gives you direct access to the <a href="http://day.com/maven/jsr170/javadocs/jcr-1.0/javax/jcr/Node.html"
class="external-link" rel="nofollow">Node</a> object. Otherwise this object is not
defined. However, we discourage using this variable as this directly binds you to the jcr
api and makes your script unusable with other data sources supported by Sling. The better
approach is to rely on the <tt>resource</tt> and the value map. Have a look at
the <tt>ResourceUtil</tt> class for more information.</p>


<h2><a name="Scriptingvariables-JSP"></a>JSP</h2>

<p>Since JSPs already have a few Java-objects pre-defined, things have to be named differently
here. And you will have to explicitly require the variables to be defined with a custom tag
<tt>&lt;sling:defineObjects /&gt;</tt>. Your jsp should start with:</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
&lt;%@ page session=<span class="code-quote">"<span class="code-keyword">false</span>"</span>
%&gt;
&lt;%@ page <span class="code-keyword">import</span>="javax.jcr.*,
        org.apache.sling.api.resource.Resource"
%&gt;
&lt;%@ taglib prefix=<span class="code-quote">"sling"</span> uri=<span
class="code-quote">"http:<span class="code-comment">//sling.apache.org/taglibs/sling/1.0"</span>
%&gt;
</span>
&lt;sling:defineObjects /&gt;
</pre>
</div></div>

<div class='table-wrap'>
<table class='confluenceTable'><tbody>
<tr>
<td class='confluenceTd'> slingRequest </td>
<td class='confluenceTd'> <a href="http://svn.apache.org/viewvc/sling/trunk/bundles/api/src/main/java/org/apache/sling/api/SlingHttpServletRequest.java?view=markup"
class="external-link" rel="nofollow">SlingHttpServletRequest</a> object, providing
access to the HTTP request header information - extends the standard <a href="http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/HttpServletRequest.html"
class="external-link" rel="nofollow">HttpServletRequest</a> - and provides access
to Sling-specific things like resource, path info, selector, etc. </td>
</tr>
<tr>
<td class='confluenceTd'> slingResponse </td>
<td class='confluenceTd'> <a href="http://svn.apache.org/viewvc/sling/trunk/bundles/api/src/main/java/org/apache/sling/api/SlingHttpServletResponse.java?view=markup"
class="external-link" rel="nofollow">SlingHttpServletResponse</a> object, providing
access for the HTTP response that is created by the server. This is currently the same as
the <a href="http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/HttpServletResponse.html"
class="external-link" rel="nofollow">HttpServletResponse</a> from which it extends.
</td>
</tr>
<tr>
<td class='confluenceTd'> request </td>
<td class='confluenceTd'> The standard JSP request object which is a pure <a href="http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/HttpServletRequest.html"
class="external-link" rel="nofollow">HttpServletRequest</a>. </td>
</tr>
<tr>
<td class='confluenceTd'> response </td>
<td class='confluenceTd'> The standard JSP response object which is a pure <a href="http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/HttpServletResponse.html"
class="external-link" rel="nofollow">HttpServletResponse</a>. </td>
</tr>
<tr>
<td class='confluenceTd'> resourceResolver </td>
<td class='confluenceTd'> Current <a href="http://svn.apache.org/viewvc/sling/trunk/bundles/api/src/main/java/org/apache/sling/api/resource/ResourceResolver.java?view=markup"
class="external-link" rel="nofollow">ResourceResolver</a>. Same as <tt>slingRequest.getResourceResolver()</tt>.
</td>
</tr>
<tr>
<td class='confluenceTd'> sling </td>
<td class='confluenceTd'> <a href="http://svn.apache.org/viewvc/sling/trunk/bundles/api/src/main/java/org/apache/sling/api/scripting/SlingScriptHelper.java?view=markup"
class="external-link" rel="nofollow">SlingScriptHelper</a>, containing convenience
methods for scripts, mainly <tt>sling.include('/some/other/resource')</tt> for
including the responses of other resources inside this response (eg. embedding header html
snippets) and <tt>sling.getService(foo.bar.Service.class)</tt> to retrieve OSGi
services available in Sling (Class notation depending on scripting language). </td>
</tr>
<tr>
<td class='confluenceTd'> resource </td>
<td class='confluenceTd'> Current <a href="http://svn.apache.org/viewvc/sling/trunk/bundles/api/src/main/java/org/apache/sling/api/resource/Resource.java?view=markup"
class="external-link" rel="nofollow">Resource</a> to handle, depending on the URL
of the request. Same as <tt>slingRequest.getResource()</tt>. </td>
</tr>
<tr>
<td class='confluenceTd'> log </td>
<td class='confluenceTd'> Provides an <a href="http://www.slf4j.org/api/org/slf4j/Logger.html"
class="external-link" rel="nofollow">SLF4J Logger</a> for logging to the Sling log
system from within scripts, eg. <tt>log.info("Executing my script")</tt>.</td>
</tr>
<tr>
<td class='confluenceTd'> bindings </td>
<td class='confluenceTd'> Provides access to the <a href="http://svn.apache.org/viewvc/sling/trunk/bundles/api/src/main/java/org/apache/sling/api/scripting/SlingBindings.java?view=markup"
class="external-link" rel="nofollow">SlingBindings</a> object for access to non-standard
scripting variables.</td>
</tr>
</tbody></table>
</div>


<p>In addition currently the <tt>currentNode</tt> binding is supported.
If the current <tt>resource</tt> points to a JCR node (which is typically the
case in Sling), this gives you direct access to the <a href="http://day.com/maven/jsr170/javadocs/jcr-1.0/javax/jcr/Node.html"
class="external-link" rel="nofollow">Node</a> object. Otherwise this object is not
defined. However, we discourage using this variable as this directly binds you to the jcr
api and makes your script unusable with other data sources supported by Sling. The better
approach is to rely on the <tt>resource</tt> and the value map. Have a look at
the <tt>ResourceUtil</tt> class for more information.</p>

<p>The names of the JSP scripting variables can be altered by passing attributes to
the <tt>sling:defineObjects</tt> tag using these attributes:</p>
<div class='table-wrap'>
<table class='confluenceTable'><tbody>
<tr>
<th class='confluenceTh'>Variable Name</th>
<td class='confluenceTd'>Attribute Name</td>
</tr>
<tr>
<td class='confluenceTd'>slingRequest</td>
<td class='confluenceTd'>requestName</td>
</tr>
<tr>
<td class='confluenceTd'>slingResponse</td>
<td class='confluenceTd'>responseName</td>
</tr>
<tr>
<td class='confluenceTd'>resource</td>
<td class='confluenceTd'>resourceName</td>
</tr>
<tr>
<td class='confluenceTd'>currentNode</td>
<td class='confluenceTd'>nodeName</td>
</tr>
<tr>
<td class='confluenceTd'>sling</td>
<td class='confluenceTd'>slingName</td>
</tr>
<tr>
<td class='confluenceTd'>resourceResolver</td>
<td class='confluenceTd'>resourceResolverName</td>
</tr>
<tr>
<td class='confluenceTd'>log</td>
<td class='confluenceTd'>logName</td>
</tr>
<tr>
<td class='confluenceTd'>bindings</td>
<td class='confluenceTd'>bindingsName</td>
</tr>
</tbody></table>
</div>


<p>For example, to specify that the <tt>Logger</tt> object should be available
as a scripting variable named <tt>logger</tt> (instead of <tt>log</tt>):</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
&lt;sling:defineObject logName=<span class="code-quote">"logger"</span>/&gt;
</pre>
</div></div>


<h3><a name="Scriptingvariables-ResourceInclusion"></a>Resource Inclusion</h3>

<p>Instead of <tt>sling.include("/path/to/resource")</tt> you can use the
sling taglib for that:</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
&lt;sling:include path=<span class="code-quote">"/path/to/resource"</span>
/&gt; 
</pre>
</div></div>

<p>For more options of the sling taglib see the <a href="http://svn.apache.org/viewvc/sling/trunk/bundles/scripting/jsp-taglib/src/main/resources/META-INF/taglib11.tld?view=markup"
class="external-link" rel="nofollow">tag lib definition file</a>.</p>

<h2><a name="Scriptingvariables-ESP"></a>ESP</h2>

<p>Here's a few of the objects and methods available in an ESP file:</p>

<div class="code panel" style="border-style: solid;border-width: 1px;"><div class="codeHeader
panelHeader" style="border-bottom-width: 1px;border-bottom-style: solid;"><b>html.esp</b></div><div
class="codeContent panelContent">
<pre class="code-java">
&lt;html&gt;
&lt;head&gt;&lt;title&gt;Sling ESP reference documentation&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
	
&lt;h2&gt;Sling ESP documentation (work in progress)&lt;/h2&gt;
&lt;p&gt;Have a look at <span class="code-keyword">this</span> file's
source or at Sling's ScriptableNodeTest.java&lt;/p&gt;&lt;br/&gt;
	
&lt;%= 'tags: use \&lt;%=  %\&gt; to evaluate, \&lt;%  %\&gt; otherwise.'
%&gt;
&lt;%  'e.g. <span class="code-keyword">this</span> will not be printed';
%&gt;&lt;br/&gt;
&lt;%

<span class="code-comment">// create a <span class="code-keyword">new</span>
node under currentNode
</span><span class="code-keyword">var</span> n = currentNode.addNode('n');
prt('path of n: ' + n.getPath());

<span class="code-comment">// create <span class="code-keyword">new</span>
node and specify node type
</span><span class="code-keyword">var</span> n2 = n.addNode('n2', 'nt:folder');

<span class="code-comment">// set and get property
</span>n.setProperty('thename', 'thevalue');
prt('get prop thename: ' + n['thename']               ); <span class="code-comment">//
thevalue
</span>prt('another way: '      + n.thename                  ); <span class="code-comment">//
thevalue
</span>prt('get type of n2:  '  + n2['jcr:primaryType']      ); <span class="code-comment">//
nt:folder
</span>prt('test type of n2: '  + n2.isNodeType('nt:folder') ); <span class="code-comment">//
<span class="code-keyword">true</span>
</span>
<span class="code-comment">// iterate over properties
</span><span class="code-keyword">var</span> props = n.getProperties();
<span class="code-keyword">for</span>(i in props) { 
  prt('getProperties(): ' + props[i].name + ': ' + props[i].value.string); 
}

<span class="code-comment">// getNodes()
</span>n.addNode('abcd');
n.addNode('abcdef')
n.addNode('abcdefgh');
prt('get all nodes: ' +n.getNodes().length         ); <span class="code-comment">//
4, incl n2	
</span>prt('get abcd: '      +n.getNodes('abcd').length   ); <span class="code-comment">//
1, abcd
</span>prt('get abcde*: '    +n.getNodes('abcde*').length ); <span class="code-comment">//
2, abcdef and abdefgh
</span>
<span class="code-comment">// remove()
</span>n.getNode('abcd').remove();
prt('removed abcd node ' + n.hasNode('abcd'));				<span class="code-comment">// <span
class="code-keyword">false</span>
</span>
<span class="code-comment">// get the root node (3 ways)
</span>prt( currentNode.getAncestor(0));
prt( currentNode.session.getRootNode());
prt( currentNode.getSession().getRootNode());

<span class="code-comment">// include the rendered result of another node (see Sling
in 15 minutes)
</span><span class="code-comment">// sling.include(<span class="code-quote">"/content/header"</span>,
<span class="code-quote">"forceResourceType=wiki.page,replaceSelectors=edit,replaceSuffix=validation"</span>);
</span>
function prt(s) { out.print(s+'&lt;br/&gt;&lt;br/&gt;'); }
%&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
</div></div>

<h2><a name="Scriptingvariables-Groovy"></a>Groovy</h2>

<p>An enhanced version of the GET.groovy script from <a href="http://sling.apache.org/site/groovy-support.html"
class="external-link" rel="nofollow">http://sling.apache.org/site/groovy-support.html</a>
that shows all the variables and a little of what's groovy about Groovy.</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
response.setContentType(<span class="code-quote">"text/html"</span>);
response.setCharacterEncoding(<span class="code-quote">"UTF-8"</span>);

log.info <span class="code-quote">"Groovin' on ${resource}"</span>

def mb = <span class="code-keyword">new</span> groovy.xml.MarkupBuilder(out)

mb.html {

   <span class="code-comment">// Shouldn't javax.jcr.Property.getString() take care
of <span class="code-keyword">this</span> <span class="code-keyword">for</span>
us?
</span>   def formatMultipleValues = { prop -&gt;
      <span class="code-keyword">if</span> (prop.definition.isMultiple()) {
         prop.values.string.join('; ')
      } <span class="code-keyword">else</span> {
         prop.string
      }
   }
   
   def tableForMap = { cap, map -&gt;
      table {
         caption { h2 cap }
         tr { th 'property' ; th 'value' }
         map.each { key, value -&gt; tr { td key ; td value } }
      }
   }

   meta {
      title 'Groovy Scripting Sample <span class="code-keyword">for</span> Sling'
   }
   body {
      h1 <span class="code-quote">"Hello World !"</span> 
      p <span class="code-quote">"This is Groovy Speaking"</span> 
      p <span class="code-quote">"You requested the Resource ${resource} (yes, <span
class="code-keyword">this</span> is a GString)"</span>

      <span class="code-comment">// If we get called on a system file, then there won't
be a currentNode binding.
</span>      <span class="code-keyword">if</span> (<span class="code-keyword">this</span>.binding.variables.containsKey('currentNode'))
{
         table {
            caption { h2 'Current Node Properties' }
            tr { th 'property' ; th 'value' }
            currentNode.properties.each { prop -&gt; tr { td prop.name ; td formatMultipleValues(prop)
} }
         }
      }
      tableForMap 'Resource Properties', resource.properties
      tableForMap 'Script Bindings', <span class="code-keyword">this</span>.binding.variables
      tableForMap 'Request Properties', request.properties
   }
}
</pre>
</div></div>

<p>And what's up with the Java Content Repository API not using the Java Collections
API?  A repository is a collection after all.  Not very groovy...</p>

<p>Here's another example of using Groovy's MarkupBuilder with Sling <a href="http://n1ceone.blogspot.com/2008/09/using-groovy-builders-in-sling.html"
class="external-link" rel="nofollow">http://n1ceone.blogspot.com/2008/09/using-groovy-builders-in-sling.html</a>.</p>
    </div>
        <div id="commentsSection" class="wiki-content pageSection">
        <div style="float: right;">
            <a href="https://cwiki.apache.org/confluence/users/viewnotifications.action"
class="grey">Change Notification Preferences</a>
        </div>
        <a href="https://cwiki.apache.org/confluence/display/SLING/Scripting+variables">View
Online</a>
        |
        <a href="https://cwiki.apache.org/confluence/pages/diffpagesbyversion.action?pageId=90231&revisedVersion=19&originalVersion=18">View
Changes</a>
                |
        <a href="https://cwiki.apache.org/confluence/display/SLING/Scripting+variables?showComments=true&amp;showCommentArea=true#addcomment">Add
Comment</a>
            </div>
</div>
</div>
</div>
</div>
</body>
</html>

Mime
View raw message