在 Sightly AEM 中评估表达式并作为参数传递

Evaluating expression and pass as argument in Sightly AEM

我有以下 Sightly 表达式:

 <li data-sly-call="${linkTemplate.dynamicLink @ section='education', 
    url='/en/life-career-events.html', text=${'comp.masthead.navigation.home' @ i18n}}">
 </li>

dynamiclink模板如下:

<div data-sly-template.dynamicLink="${@ section, url, text}"
     data-sly-use.membersNav="${'com.comp.cms.component.masthead.MembersNavigation' @ section=section}">
  <a data-sly-attribute.class="${membersNav.cssClass}" href="${url}">${text}</a>
</div>

这不起作用,因为 text=${'comp.masthead.navigation.home' @ i18n} 未被评估为字符串,然后传递到动态链接中。

这可能吗?当我想评估 i18n 查找时,我可以评估并分配给一个变量还是必须创建一个新模板?

Sightly 1.1 不允许在表达式中包含表达式,目前没有更改的计划。

破解解决方案:

有一个技巧:data-sly-test 可以(滥用)用于设置变量。不过,除非您有实际情况,否则这并不是真正推荐的方法,因为这会误导阅读模板的人,认为其意图是要有实际情况。

技巧是这样的:可以向 data-sly-test 提供一个标识符,这会将测试结果公开为一个变量。此外,除非结果字符串为空,否则 data-sly-test 将被视为 true。

例如:

<p data-sly-test.spanishAsset="${'Asset' @ i18n, locale='es'}">${spanishAsset}</p>

输出:

<p>Recurso</p>

所以在你的情况下,你可以这样写:

<li data-sly-test.linkText="${'comp.masthead.navigation.home' @ i18n}"
    data-sly-call="${linkTemplate.dynamicLink @ section='education', 
url='/en/life-career-events.html', text=linkText}">
</li>

更清洁的解决方案

因为您可能不想向此模板的所有用户解释他们必须编写这样的 hack,而不是为翻译文本和非翻译文本使用两个单独的模板,您可以利用可选的模板参数。所以你可能会有一个 noI18n 可选参数。

调用将尽可能简单:

<!--/* Translating would be the default behavior */-->
<li data-sly-call="${linkTemplate.dynamicLink @
    section='education', 
    url='/en/life-career-events.html',
    text='comp.masthead.navigation.home'}"></li>
<!--/* Or translating could be turned off */-->
<li data-sly-call="${linkTemplate.dynamicLink @
    section='education', 
    url='/en/life-career-events.html',
    text='my text...',
    noI18n=true}"></li>

模板将针对这两种情况具有两个 data-sly-test 条件(请注意,在 AEM 6.1+ 中可以删除 data-sly-unwrap 属性):

<div data-sly-template.dynamicLink="${@ section, url, text, noI18n}"
     data-sly-use.membersNav="${'com.comp.cms.component.masthead.MembersNavigation'
         @ section=section}">
    <a href="${url}" data-sly-attribute.class="${membersNav.cssClass}">
        <sly data-sly-test="${noI18n}" data-sly-unwrap>${membersNav.text}</sly>
        <sly data-sly-test="${!noI18n}" data-sly-unwrap>${membersNav.text @ i18n}</sly>
    </a>
</div>

可选地,为了使模板尽可能简单并删除这些条件,您还可以使 Use-API 进行翻译,具体取决于 noI18n 可选参数:

<div data-sly-template.dynamicLink="${@ section, url, text, noI18n}"
     data-sly-use.membersNav="${'com.comp.cms.component.masthead.MembersNavigation'
         @ section=section, noI18n=noI18n}">
    <a href="${url}" data-sly-attribute.class="${membersNav.cssClass}">
        ${membersNav.text}
    </a>
</div>

翻译字符串的逻辑的正确代码是:

Locale pageLang = currentPage.getLanguage(false);
I18n i18n = new I18n(slingRequest.getResourceBundle(pageLang));
String text = i18n.get("Enter a search keyword");