如何在HTML属性的代码中添加条件逻辑

Rah*_*hul 1 aem sightly

我试着搜索,但不知怎的,我无法思考我需要使用健全的代码在html元素中添加动态标签.不确定这是不是好的做法,但想问一下.现在我知道如何将cssclass应用于href中的class属性.但是如果我想在href中注入整个属性"class ='one'"怎么办呢?

可以做到这一点.我知道我可以做点什么

<a href="${properties['jcr:titleurl']}" class="${properties.openinnewwindow ? 'nonunderline' : ''}"> <h3>${properties['jcr:title']}</h3></a>
Run Code Online (Sandbox Code Playgroud)

但我想这样做,

<div class="col-md-12">       
<a href="${properties['jcr:titleurl']}"  data-sly-test="${properties.openinnewwindow ? 'class=one' : class='two'}"> <h3>${properties['jcr:title']}</h3></a>
Run Code Online (Sandbox Code Playgroud)

nat*_*les 6

使用data-sly-test以确定是否保留或删除元素,所以它不是你要找的内容.

您提到如果变量为null或空白,则不需要class属性.您使用三元运算符提供的代码就是这样做的.

<a href="#" class="${properties.openinnewwindow ? 'nonunderline' : ''}">link</a>
Run Code Online (Sandbox Code Playgroud)

在truthy/falsey的概念中,Sightly非常像JavaScript.在你的例子中,如果openinnewwindow是真实的(真,非空,或未定义,等等......),则class属性将等于nonunderline.如果openinnewwindow为false,则class属性不会出现在呈现的HTML中.

编写此代码的另一种方法是使用逻辑&&运算符.这个语法是你要求的:

<a href="#" class="${properties.openinnewwindow && 'nonunderline'}">link</a>
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅Sightly规范.