如何在data-sly-list中添加条件元素?

时间:2015-08-16 03:24:18

标签: aem sightly

我目前有一个数据狡猾列表,可以像这样填充JS数组:

          var infoWindowContent = [
              <div data-sly-use.ed="Foo"
                   data-sly-list="${ed.allassets}"
                   data-sly-unwrap>
                   ['<div class="info_content">' +
                   '<h3>${item.assettitle @ context='unsafe'}</h3> ' +
                   '<p>${item.assettext @ context='unsafe'} </p>' + '</div>'],
               </div>
               ];

我需要在这个数组中添加一些逻辑。如果assetFormat属性只是'text / html',那么我想打印<p>标记。如果assetFormat属性为image/png,那么我想打印img标记。

我的目标是这样的。这有可能实现吗?

          var infoWindowContent = [
              <div data-sly-use.ed="Foo"
                   data-sly-list="${ed.allassets}"
                   data-sly-unwrap>
                   ['<div class="info_content">' +
                   '<h3>${item.assettitle @ context='unsafe'}</h3> ' +
                   if (assetFormat == "image/png")
                       '<img src="${item.assetImgLink}</img>'
                   else if (assetFormat == "text/html")
                       '<p>${item.assettext @ context='unsafe'}</p>'
                   + '</div>'],
               </div>
               ];

1 个答案:

答案 0 :(得分:4)

要快速回答您的问题,是的,您可以在列表中找到条件(data-sly-test),如下所示:

<div data-sly-list="${ed.allAssets}">
    <h3>${item.assettitle @ context='html'}</h3>
    <img data-sly-test="${item.assetFormat == 'image/png'}" src="${item.assetImgLink}"/>
    <p data-sly-test="${item.assetFormat == 'text/html'}">${item. assetText @ context='html'}"</p>
</div>

但是看看你尝试做什么,基本上是在客户端而不是服务器上进行渲染,让我退一步找到比使用Sightly生成JS代码更好的解决方案。 / p>

编写好的Sightly模板的一些经验法则:

  • 尽量不要在模板中混合HTML,JS和CSS:Sightly is on 目的仅限于HTML,因此输出JS或CSS非常差。 因此,生成JS对象的逻辑应该在 使用API​​,使用一些前面提到的便利API,比如 JSONWriter
  • 除非您自己以某种方式过滤掉该字符串,否则请尽可能避免任何@context='unsafe'。每个字符串都不是 escaped or filtered可以在XSS attack中使用{{3}}。这个 即使只有AEM作者可以输入该字符串, 因为他们也可能成为攻击的受害者。为了安全,一个系统 不应该希望他们的用户都不会被黑客入侵。如果您想允许某些HTML,请改用@context='html'

将信息传递给JS的好方法通常是使用数据属性。

<div class="info-window"
     data-sly-use.foo="Foo"
     data-content="${foo.jsonContent}"></div>

对于JS中的标记,我宁愿将其移动到客户端JS,以便相应的Foo.java逻辑仅构建JSON内容,而不在内部进行任何标记。

package apps.MYSITE.components.MYCOMPONENT;

import com.adobe.cq.sightly.WCMUsePojo;
import org.apache.sling.commons.json.io.JSONStringer;
import com.adobe.granite.xss.XSSAPI;

public class Foo extends WCMUsePojo {
    private JSONStringer content;

    @Override
    public void activate() throws Exception {
        XSSAPI xssAPI = getSlingScriptHelper().getService(XSSAPI.class);

        content = new JSONStringer();
        content.array();
        // Your code here to iterate over all assets
        for (int i = 1; i <= 3; i++) {
            content
                .object()
                .key("title")
                // Your code here to get the title - notice the filterHTML that protects from harmful HTML
                .value(xssAPI.filterHTML("title <span>" + i + "</span>"));

            // Your code here to detect the media type
            if ("text/html".equals("image/png")) {
                content
                    .key("img")
                    // Your code here to get the asset URL - notice the getValidHref that protects from harmful URLs
                    .value(xssAPI.getValidHref("/content/dam/geometrixx/icons/diamond.png?i=" + i));
            } else {
                content
                    .key("text")
                    // Your code here to get the text - notice the filterHTML that protects from harmful HTML
                    .value(xssAPI.filterHTML("text <span>" + i + "</span>"));
            }

            content.endObject();
        }
        content.endArray();
    }

    public String getJsonContent() {
        return content.toString();
    }
}

然后,位于相应客户端库中的客户端JS将获取数据属性并写入相应的标记。显然,避免将JS内联到HTML中,或者我们再次混合应该保持分离的内容。

jQuery(function($) {
    $('.info-window').each(function () {
        var infoWindow = $(this);
        var infoWindowHtml = '';

        $.each(infoWindow.data('content'), function(i, content) {
            infoWindowHtml += '<div class="info_content">';
            infoWindowHtml += '<h3>' + content.title + '</h3>';
            if (content.img) {
                infoWindowHtml += '<img alt="' + content.img + '">';
            }
            if (content.text) {
                infoWindowHtml += '<p>' + content.title + '</p>';
            }
            infoWindowHtml += '</div>';
        });

        infoWindow.html(infoWindowHtml);
    });
});

这样,我们将该信息窗口的完整逻辑移动到客户端,如果它变得更复杂,我们可以使用一些客户端模板系统,如Handlebars。服务器Java代码不需要知道标记,只需输出所需的JSON数据,而Sightly模板只负责输出服务器端渲染的标记。

相关问题