Skip to content

Instantly share code, notes, and snippets.

@auniverseaway
Last active September 13, 2015 00:28
Show Gist options
  • Save auniverseaway/0fe4b7148bd92663d740 to your computer and use it in GitHub Desktop.
Save auniverseaway/0fe4b7148bd92663d740 to your computer and use it in GitHub Desktop.
Detect String Array in Sightly
<template data-sly-template.view>
<sly data-sly-test="${properties.options[1]}" data-sly-list.child="${properties.options}" data-sly-unwrap>
<label><input type="checkbox" name="${properties.name}" value="${child}">${child}</label>
</sly>
<label data-sly-test="${!properties.options[1]}"><input type="checkbox" name="${properties.name}" value="${properties.options}">${properties.options}</label>
</template>
@gabrielwalt
Copy link

In Sigthly 1.1, data-sly-list and data-sly-repeat also iterate (once) over non-iterable elements:

<ul class="one" data-sly-list="${'foo'}">
    <li>${item}</li>
</ul>
<ul class="two" data-sly-list="${['foo', 'bar']}">
    <li>${item}</li>
</ul>

will output:

<ul class="one">
    <li>foo</li>
</ul>
<ul class="two">
    <li>foo</li>
    <li>bar</li>
</ul>

So in your case, you should be able to simply write your template as follows:

<label data-sly-repeat="${properties.options}">
    <input type="checkbox" name="${properties.name}" value="${item}"/> ${item}
</label>

@gabrielwalt
Copy link

Now if you have Sightly 1.0 (and not 1.1), then what you do is very clever, but I'd rather use a very simple Use-API to detect if it is an array or not, and keep the template as straightforward as possible:

<sly data-sly-template.view data-sly-use.logic="${'logic.js' @ options=properties.options}" data-sly-list="${logic.options}">
    <label><input type="checkbox" name="${properties.name}" value="${item}"/> ${item}</label>
</sly>

logic.js:

use(function () {
    var options = this.options;
    return {
        options: Array.isArray(options) ? options : [options]
    }
});

@auniverseaway
Copy link
Author

Just a heads up that Array.isArray was returning my String[] in JCR as a comma separated string. I had to change it a little...

logic.js:

use(function () {
    var options = this.options;
    return {
        options : options.constructor === Array ? options : [options]
    }
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment