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

标签 aem sightly

我目前有一个 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' 然后我想打印 <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>
               ];

最佳答案

为了快速回答您的问题,是的,您可以在列表中添加一个条件(使用 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 模板仅负责输出服务器端呈现的标记。

关于aem - 如何在 data-sly-list 中添加条件元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32031510/

相关文章:

java - 如何在不使用 javascript 的情况下在 sightly 页面中使用 sling 服务?

arithmetic-expressions - Sightly 真的不支持任何算术运算符吗?

aem - data-sly-use、data-sly-resource、data-sly-include 和 data-sly-template 之间有什么区别?

aem - 给定路径,在 Sightly 中获取对资源的引用

java - 为什么将响应 header 设置为调度程序不起作用

apache - 在 Windows 中启用 Apache 中的 mod_headers

mime-types - 在 cq5/AEM 中创建自定义 MIME 类型

aem - 使用 Sling 模型时使用 Sling 的 AdaptTo 方法时出现错误

aem - 如何以编程方式创建新版本的 CQ5 页面?

javascript - 暂停按钮功能在轮播中不起作用