nogamawa
nogamawa

Reputation: 145

Best practice for JSF 2 dynamic Menu handling?

i am looking for a best practice handling a simple menu with JSF and CDI.

I would like to have a top menu with dynamic entries. Something like (from the main template):

            <ul>
                <c:forEach var="menuItem" items="#{navigationBean.topMenuItems}">
                    <c:choose>
                        <c:when test="#{navigationBean.isSelectedTop(menuItem.name)}">
                            <li class="current_page_item"><h:outputLink value="#{menuItem.url}"><h:outputText value="#{menuItem.name}" /></h:outputLink></li>
                        </c:when>
                        <c:otherwise>
                            <li><h:outputLink value="#{menuItem.url}"><h:outputText value="#{menuItem.name}" /></h:outputLink></li>
                        </c:otherwise>
                    </c:choose>
                </c:forEach>
            </ul>

NavigationBean (Sessionscoped, and holding a list of NavigationItems) and NavigationItem are only beans. Then opening another view I set the current view ID as selected within the navigatiobean:

@PostConstruct 
private void init (){

    navigation.setSelectedTopMenu(getViewId());
}

The problem is, it is too late. The page is already rendered and no view id is selected.

Is this approach not good at all? Are there any best practices? Searching for JSF menu and JSF navigation leads to other problems, so I couldn't find anything.

Thanks in advance!

Upvotes: 1

Views: 5305

Answers (1)

MarrLiss
MarrLiss

Reputation: 808

One way is to use component binding (for example to h:panelGroup) and whole menu generate in binding method.

JSF page:

<h:panelGroup binding="navigationBean.navigationMenu" />

Bean:

public HtmlPanelGroup getNavigationMenu() {
     HtmlPanelGroup menu = new HtmlPanelGroup();
     menu.setId("menu");
     HtmlOutputLink link = new HtmlOutputLink();
     // ... other components etc.
     menu.getChildren().add(link);
}

Upvotes: 2

Related Questions