3

我有以下 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 查找时,我可以评估并分配给一个变量还是必须创建一个新模板?

4

1 回答 1

3

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

破解解决方案:

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

诀窍是这样的:可以向 提供一个标识符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条件(请注意,data-sly-unwrap可以在 AEM 6.1+ 中删除属性):

<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");
于 2015-08-17T23:49:20.457 回答