根据对话框使组件可链接或不可链接

  • 本文关键字:链接 组件 对话框 aem
  • 更新时间 :
  • 英文 :


我有一个组件,并希望在对话框中为作者提供添加链接路径的选项。 如果填写了此链接路径,那么我希望组件包装器是一个<a>标签。 如果没有填写,我希望它保持<div>

<div class="section" data-sly-test="${!properties.path}">
<img src="${properties.icon}" alt="${properties.alt}" />
<div data-sly-test="${properties.heading}">
<h2 data-sly-element="${properties.headingSize}">${properties.heading}</h2>
</div>
</div>
<a href="${properties.path}" class="section" data-sly-test="${properties.path}">
<img src="${properties.icon}" alt="${properties.alt}" />
<div data-sly-test="${properties.heading}">
<h2 data-sly-element="${properties.headingSize}">${properties.heading}</h2>
</div>
</a>

有没有比使用数据测试开关创建整个组件的两个单独构建更干净的方法? 我在很多这样的例子上挣扎过,其中包装标签/div 被对话框更改了。在这里的代码中寻找类似于数据元素在<h2>上的行为方式的东西。

有多种方法可以实现您要做的事情。

使用data-sly-elementdata-sly-attribute

如果属性的值为空/空,data-sly-attribute不会将属性添加到标记中。因此,如果路径不可用,可以如下所示使用它来用div 替换锚标记。

<a class="section" data-sly-attribute.href="${properties.path}" data-sly-element="${properties.path ? 'a' : 'div'}">
<img src="${properties.icon}" alt="${properties.alt}" />
<div data-sly-test="${properties.heading}">
<h2 data-sly-element="${properties.headingSize}">${properties.heading}</h2>
</div>
</a>

使用data-sly-unwrap

解包只会删除包含标签,而不会移除所有内部标签。因此,可以按如下所示使用。

<div class="section" data-sly-unwrap="${properties.path}">
<a href="${properties.path}" class="section" data-sly-unwrap="${!properties.path}">
<img src="${properties.icon}" alt="${properties.alt}" />
<div data-sly-test="${properties.heading}">
<h2 data-sly-element="${properties.headingSize}">${properties.heading}</h2>
</div>
</a>
</div>

使用data-sly-templatedata-sly-call

这类似于您最初编写的内容,但可以将其移动到模板并调用两次,而不是复制整个内部 HTML。

<div class="section" data-sly-test="${!properties.path}">
<sly data-sly-call="${tpl}"></sly>
</div>
<a href="${properties.path}" class="section" data-sly-test="${properties.path}">
<sly data-sly-call="${tpl}"></sly>
</a>
<!--/* The template */-->
<template data-sly-template.tpl="">
<img src="${properties.icon}" alt="${properties.alt}" />
<div data-sly-test="${properties.heading}">
<h2 data-sly-element="${properties.headingSize}">${properties.heading}</h2>
</div>
</template>

有关 HTL 块语句的更多信息,请参阅此官方文档。

最新更新