【问题标题】:How to add conditional elements in data-sly-list?如何在 data-sly-list 中添加条件元素?
【发布时间】:2015-08-16 03:24:17
【问题描述】:

我目前有一个 data-sly-list 填充这样的 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',那么我想打印&lt;p&gt; 标签。如果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>
               ];

【问题讨论】:

    标签: aem sightly


    【解决方案1】:

    要快速回答您的问题,是的,您可以在列表中添加一个条件(使用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 代码更好的解决方案。

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

    • 尽量不要在模板中混合 HTML、JS 和 CSS:Sightly 已开启 用途仅限于 HTML,因此很难输出 JS 或 CSS。 因此,生成 JS 对象的逻辑应该在 Use-API,通过使用一些为此而制定的便利 API,例如 JSONWriter
    • 还尽可能避免使用任何@context='unsafe',除非您以某种方式自己过滤该字符串。每个字符串不是 escaped or filtered 可用于XSS attack。这 即使只有 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 模板只负责输出服务器端呈现的标记。

    【讨论】:

      【解决方案2】:

      看看这里的例子,我会把这个逻辑放在一个 JS USe-api 中来填充这个数组。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-01-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-20
        相关资源
        最近更新 更多