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