אתה מציג תוכן עזרה עבור גרסה:

Handlebars Helpers (helpers) are methods callable from Handlebars scripts to facilitate working with SCF components.

The implementation includes a client-side and a server-side definition.  It is also possible for developers to create custom helpers.

The custom SCF helpers delivered with AEM Communities are defined in the client libarry :

  • /etc/clientlibs/social/commons/scf/helpers.js

הערה:

Be sure to install the latest Communities feature pack.

abbreviate

A helper to return an abbreviated string conforming to the maxWords and maxLength properties.

The string to be abbreviated is provided as the context.  If no context is provided, an empty string is returned.

First, the context is trimmed to maxLength, and then the context is sliced into words and reduced to maxWords.

If safeString is set to true, then the returned string is a SafeString.

parameters

  • context : String
    (optional) Default is the empty string
  • maxLength : number
    (optional) Default is the length of the context.
  • maxWords : number
    (optional) Default is the number of words in the trimmed string.
  • safeString : boolean
    (optional) Returns a Handlebars.SafeString() if true.  Default is false.

examples

{{abbreviate subject maxWords=2}}

/*
If subject =
    "AEM Communities - Site Creation Wizard"

Then abbreviate would return
    "AEM Communities".
*/
{{{abbreviate message safeString=true maxLength=30}}}

/*
If message =
    "The goal of AEM Communities is to quickly create a community engagement site."

Then abbreviate would return
    "The goal of AEM Communities is"
*/

content-loadmore

A helper to add two spans under a div, one for the full text and the other for the less text, with the ability to toggle between the two views.

parameters

  • context : String
    (optional) Default is the empty string.
  • numChars : number
    (optional) The number of characters to display when not displaying full text. Default is 100.
  • moreText : String
    (optional) The text to display indicating there is more text to display. Default is "more".
  • ellipsesText : String
    (optional) The text to display indicating there is hidden text. Default is "...".
  • safeString : boolean
    (optional) Boolean value indicating whether or not to apply Handlebars.SafeString() before returning the result. Default is false.

example

{{content-loadmore  context numChars=32  moreText="go on"  ellipsesText="..." }}

/*
If context = 
    "Here is the initial less content and this is more content."

Then content-loadmore would return
    "Here is the initial less content<span class="moreelipses">...</span>&nbsp;<span class="scf-morecontent"><span>and this is more content.</span>&nbsp;&nbsp;<a href="" class="scf-morelink" evt="click=toggleContent">go on</a></span>"
*/

dateUtil

A helper to return a formatted date string.

parameters

  • context : number
    (optional) a millisecond value offset from January 1, 1970 (epoch).   Default is the current date.
  • format : String
    (optional) The date format to apply.  Default is "YYYY-MM-DDTHH:mm:ss.sssZ" and the result appears as "2015-03-18T18:17:13-07:00"

examples

{{dateUtil this.memberSince format="dd MMM yyyy, hh:mm"}}

// returns "18 Mar 2015, 18:17"
{{dateUtil this.birthday format="MM-DD-YYYY"}}

// returns "03-18-2015"

equals

A helper to return content depending on an equality conditional.

parameters

  • lvalue : String
    The left-hand value to compare
  • rvalue : String
    The right-hand value to compare

example

{{#equals  value "some-value"}}
  <div>They are EQUAL!</div>
{{else}}
  <div>They are NOT equal!</div>
{{/equals}}

if-wcm-mode

A block helper that tests the current value of WCM mode against a string separated list of modes.

parameters

  • context : String
    (optional) The string to translate. Required if no default provided.
  • mode : String
    (optional) A comma separated list of WCM modes to test if set.

example

{{#if-wcm-mode mode="DESIGN, EDIT"}}
 ...
{{else}}
 ...
{{/if-wcm-mode}}

i18n

This helper overrides the Handlebars helper 'i18n'.

See also Internationalizing Strings in JavaScript Code.

parameters

  • context : String
    (optional) The string to translate. Required if no default provided.
  • default : String
    (optional) The default string to translate. Required if no context provided.
  • comment : String
    (optional) A translation hint

example

{{i18n "hello"}}
{{i18n "hello" comment="greeting" default="bonjour"}}

include

A helper to include a component as a non-existing resource in a template.

This allows the resource to be programmatically customized more easily than is possible for a resource added as a JCR node. See Add or Include a Communities Component.

Only a select few of Communities components are includable.  For AEM 6.1, those that are includable are comments, rating, reviews, and voting.

This helper, appropriate only on the server-side, provides functionality similar to cq:include for JSP scripts.

parameters

  • context : String or object
    (optional, unless providing a relative path)
    use this to pass the current context
    use this.id to obtain the resource at id for rendering the resourceType requested
  • resourceType : String
    (optional) resource type will default to resource type from context
  • template : String
    path to component script
  • path : String
    (required) The path to the resource. If path is relative, a context must be provided, else the empty string is returned.
  • authoringDisabled : boolean
    (optional) Default is false. For internal use only.

example

{{include this.id path="comments" resourceType="social/commons/components/hbs/comments"}}

This will include a new comments component at this.id + /comments

includeClientLib

A helper that includes an AEM html client library, which can be a js, a css or a theme library. For multiple inclusions of different types, for example js and css, this tag needs to be used multiple times in the Handlebars script.

This helper, appropriate only on the server-side, provides functionality similar to ui:includeClientLib for JSP scripts.

parameters

  • categories : String
    (optional) A list of comma-separated client lib categories. This will include all Javascript and CSS libraries for the given categories. The theme name is extracted from the request.
  • theme : String
    (optional) A list of comma-separated client lib categories. This will include all theme related libraries (both CSS and JS) for the given categories. The theme name is extracted from the request.
  • js : String
    (optional) A list of comma-separated client lib categories. This will include all Javascript libraries for the given categories.
  • css : String
    (optional) A list of comma-separated client lib categories. This will include all CSS libraries for the given categories.

examples

// all: js + theme (theme-js + css) 
{{includeClientLib categories="cq.social.hbs.comments, cq.social.hbs.voting"}}

// returns
    <link href="/etc/clientlibs/social/hbs/tally/voting.css" rel="stylesheet" type="text/css">
    <link href="/etc/clientlibs/social/hbs/socialgraph.css" rel="stylesheet" type="text/css">
    <link href="/etc/clientlibs/social/hbs/comments.css" rel="stylesheet" type="text/css">
    <script src="/etc/clientlibs/social/hbs/tally/voting.js" type="text/javascript"></script>
    <script src="/etc/clientlibs/social/hbs/socialgraph.js" type="text/javascript"></script>
    <script src="/etc/clientlibs/social/hbs/comments.js" type="text/javascript"></script>

// only js libs
{{includeClientLib js="cq.social.hbs.comments, cq.social.hbs.voting"}}

// returns
    <script src="/etc/clientlibs/social/hbs/tally/voting.js" type="text/javascript"></script>
    <script src="/etc/clientlibs/social/hbs/socialgraph.js" type="text/javascript"></script>
    <script src="/etc/clientlibs/social/hbs/comments.js" type="text/javascript"></script>

// theme only (theme-js + css) 
{{includeClientLib theme="cq.social.hbs.comments, cq.social.hbs.voting"}}

// returns
    <link href="/etc/clientlibs/social/hbs/tally/voting.css" rel="stylesheet" type="text/css">
    <link href="/etc/clientlibs/social/hbs/comments.css" rel="stylesheet" type="text/css">
    <script src="/etc/clientlibs/social/hbs/tally/voting.js" type="text/javascript"></script>
    <script src="/etc/clientlibs/social/hbs/comments.js" type="text/javascript"></script>

// css only
{{includeClientLib css="cq.social.hbs.comments, cq.social.hbs.voting"}}

// returns
    <link href="/etc/clientlibs/social/hbs/tally/voting.css" rel="stylesheet" type="text/css">
    <link href="/etc/clientlibs/social/hbs/socialgraph.css" rel="stylesheet" type="text/css">
    <link href="/etc/clientlibs/social/hbs/comments.css" rel="stylesheet" type="text/css">

pretty-time

A helper to display how much time has passed up to a cutoff point, after which a regular date format is displayed.

For example :

  • 12 hours ago
  • 7 days ago

parameters

  • context : number
    A time in the past to compare to 'now'. Time is expressed as a millisecond value offset from January 1, 1970 (epoch).
  • daysCutoff : number
    The number of days ago before switching to an actual date. Default is 60.

example

{{pretty-time this.published daysCutoff=7}}

/*
Depending on how long in the past, may return
  
  "3 minutes ago"

  "3 hours ago"

  "3 days ago"
*/

xss-html

A helper that encodes a source string for HTML element content to help guard against XSS.

NOTE: this is not a validator and is not to be used for writing attribute values.

parameters

  • context : object
    the HTML to encode

example

<p>{{xss-html forum-ugc}}</p>

xss-htmlAttr

A helper that encodes a source string for writing to an HTML attribute value to help guard against XSS.

NOTE: this is not a validator and is not to be used for writing actionalable attributes (href, src, event handlers).

parameters

  • context : object
    the HTML to encode

example

<div id={{xss-htmlAttr id}} />

xss-jsString

A helper that encodes a source string for writing to JavaScript string content to help guard against XSS.

NOTE: this is not a validator and is not to be used for writing to arbitrary JavaScript.

parameters

  • context : object
    the HTML to encode

example

var input = {{xss-jsString topic-title}}

xss-validHref

A helper that sanitizes an URL for writing as an HTML href or srce attribute value to help guard against XSS.

NOTE: this may return an empty string

parameters

  • context : object
    the URL to sanitize

example

<a href="{{xss-validHref url}}">my link</a>

Handlebars.js Basic Overview

A quick overview of helper functions from Handlebars.js documentation

  • A Handlebars helper call is a simple identifier (the name of the helper), followed by zero or more space-separated parameters.
  • Parameters may be a simple String, number, boolean, or JSON object, as well as an optional sequence of key-value pairs (hash arguments) as the last parameter(s).
  • The keys in hash arguments must be simple identifiers.
  • The values in hash arguments are Handlebars expressions : simple identifiers, paths, or Strings.
  • The current context, this, is always available to Handlebars helpers.
  • The context may be a String, number, boolean, or a JSON data object.
  • It is possible to pass an object nested within the current context as the context, such as this.url or this.id (see following examples of simple and block helpers).
  • Block helpers are functions that can be called from anywhere in the template.  They can invoke a block of the template zero or more times with a different context each time.  They contain a context between {{#name}} and {{/name}}.
  • Handlebars provides a final parameter to helpers named 'options'.  The special object 'options' includes
    • optional private data (options.data)
    • optional key-value properties from the call (options.hash)
    • ability to invoke itself (options.fn()) 
    • ability to invoke the inverse of itself (options.inverse())
  • It is recommended that the HTML String content returned from a helper is a SafeString.

An example of a simple helper from Handlebars.js documentation :

Handlebars.registerHelper('link_to', function(title, options) {
    return new Handlebars.SafeString('<a href="/posts' + this.url + '">' + title + "!</a>");
});

var context = {posts: [
    {url: "/hello-world",
      body: "Hello World!"}
  ] };

// when link_to is called, posts is the current context
var source = '<ul>{{#posts}}<li>{{{link_to "Post"}}}</li>{{/posts}}</ul>'

var template = Handlebars.compile(source);

template(context);

Would render:

 <ul>
   <li><a href="/posts/hello-world">Post!</a></li>
 </ul>

An example of a block helper from Handlebars.js documentation :

Handlebars.registerHelper('link', function(options) {
    return new Handlebars.SafeString('<a href="/people/' + this.id + '">' + options.fn(this) + '</a>');
});

var data = { "people": [
  { "name": "Alan", "id": 1 },
  { "name": "Yehuda", "id": 2 }
]};

// when link is called, people is the current context
var source = "<ul>{{#people}}<li>{{#link}}{{name}}{{/link}}</li>{{/people}}</ul>";

var template = Handlebars.compile(source);

template(data);

Would render:
 <ul>
   <li><a href="/people/1">Alan</a></li>
   <li><a href="/people/2">Yehuda</a></li>
 </ul>

Custom SCF Helpers

Custom helpers must be implemented on the server-side as well as the client-side, especially when passing data.  For SCF, most templates are compiled and rendered on the server-side as the server generates the HTML for a given component when the page is requested.

Server-side Custom Helpers

To implement and register a custom SCF helper on the server-side, simply implement the Java interface TemplateHelper, make it an OSGi Service and install it as part of an OSGi bundle.


For example :

FooTextHelper.java

/** Custom Handlebars Helper */

package com.my.helpers;

import java.io.IOException;

import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Service;

import com.adobe.cq.social.handlebars.api.TemplateHelper;
import com.github.jknack.handlebars.Options;

@Service
@Component
public class FooTextHelper implements TemplateHelper<String>{

    @Override
    public CharSequence apply(String context, Options options) throws IOException {
        return "foo-" + context;
    }

    @Override
    public String getHelperName() {
        return "foo-text";
    }

    @Override
    public Class<String> getContextType() {
        return String.class;
    }
}

הערה:

A helper created for the server-side must also be created for the client-side.

The component gets re-rendered on the client-side for the logged in user, and if the client-side helper is not found, the component disappears.

Client-side Custom Helpers

The client-side helpers are Handlebars scripts registered by invoking Handlebars.registerHelper().
For example :

custom-helpers.js

function(Handlebars, SCF, $CQ) {

    Handlebars.registerHelper('foo-text', function(context, options) {
        if (!context) {
            return "";
        }
        return "foo-" + context;
    });

})(Handlebars, SCF, $CQ);

The custom client-side helpers must be added to a custom client library.
The clientlib must :

  • include a dependency on cq.social.scf
  • load after Handlebars has been loaded
  • be included

Note: the SCF helpers are defined in /etc/clientlibs/social/commons/scf/helpers.js.

עבודה זו בוצעה ברישיון של Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License  הודעות המתפרסמות ב- Twitter™‎ ו- Facebook אינן מכוסות בתנאי Creative Commons.

הצהרות משפטיות   |   מדיניות פרטיות מקוונת