爪哇
@Inject
private ComponentResources resources;
public boolean isActiveMenuItemIndex() {
String item = resources.getPageName().toString();
return item.contains("Index");
}
TML
<t:if test="${activeMenuItemIndex}">
<li class="active">
<t:pageLink page="Index">Index</t:pageLink>
</li>
<p:else>
<li>
<t:pageLink page="Index">Index</t:pageLink>
</li>
</p:else>
</t:if>
这是我的第一个想法并且它有效,但您必须为每个项目创建一个单独的方法,并在TML中为每个项目使用t:if
标记。你有更好的解决方案吗?
答案 0 :(得分:3)
TML
<t:loop source="pages" item="page">
<li class="${liClass}">
<t:pageLink page="prop:page">${page}</t:pageLink>
</li>
</t:loop>
爪哇
@Inject
private ComponentResources resources;
@Property
private String page;
public String[] getPages() {
return new String[] { "Index", "Foo", "Bar" };
}
public String getLiClass() {
return page.equals(resources.getPageName()) ? "active" : "inactive";
}
答案 1 :(得分:0)
菜单组件的精简版:
Menu.java
public class Menu {
@Property
@Parameter(required = true, allowNull = false)
private List<String> pageNames;
@Property
private String pageName;
@Inject
private ComponentResources resources;
@Inject
private ComponentClassResolver componentClassResolver;
public boolean isActive() {
final String shortPageName = componentClassResolver.canonicalizePageName(pageName);
return resources.getPageName().equals(shortPageName);
}
public String getMenuItemClass() {
return isActive() ? "active" : "";
}
public String getMenuItemLabel() {
// get label from messages
}
}
Menu.tml
<t:container xmlns:t="http://tapestry.apache.org/schema/tapestry_5_1_0.xsd">
<t:loop source="pageNames" value="pageName">
<li class="${menuItemClass}">
<t:pageLink page="prop:pageName">${menuItemLabel}</t:pageLink>
</li>
</t:loop>
</t:container>