Book not found
Return to Documentation.
Overview
It is easy for users to get lost in a web application because every application has different layout designs and navigation styles. In traditional navigation, a user usually swiches to different functions by visiting different pages of an application, a.k.a page-based navigation. In ZK, we can have another choice to design the navigation as single desktop which doesn't need to visit different pages. In page-based navigation, users need to swich pages frequently, we should maintain a consistent page design throughout whole application to help users keep track of where they are. Luckily ZK provides Templating to keep multiple pages in the same style easily.
In this chapter, the example application we are going to build looks as follows:
The sidebar is used for navigation control. The lower 4 menu items lead you to different functions and they only change the central area's content. All other areas keep unchanged to form a consistent layout style among functions.
Templating
In our example application, we want to keep the header, the sidebar, and the footer unchanged whatever function a user chooses. Only the central area changes its content according to the function chosen by users from the sidebar.
If we put each function in a separated page, to keep mutiple pages in a consistent style, copying the duplicated part from one zul to another is hard to maintain. Fortunately, ZK provides a Templating technique that let you define a template zul and apply it to multiple zul pages afterward. All zul pages that apply the same template zul have same layout, so change the template zul can change the layout of all pages once.
The steps to use templating are:
- Create a template zul and define anchors
- Apply the template in the target zul and define zul fragments for anchors
Then when you visit the target zul page, ZK will insert those fragments to corresponding anchors upon anchor names and combine them as one page.
Create a Template
Creating a template is nothing different from creating a normal zul, but you should define one or more anchor by specifying annotation @inser() at self. You can give any name to identify an anchor that will be used to insert a zul fragment with the same anchor name later.
chapter7/pagebase/layout/template.zul
<zk>
<borderlayout hflex="1" vflex="1">
<north height="100px" border="none" >
<include src="/chapter3/banner.zul"/>
</north>
<west width="260px" border="none" collapsible="true" splittable="true" minsize="300">
<include src="/chapter7/pagebase/layout/sidebar.zul"/>
</west>
<center id="mainContent" autoscroll="true" border="none" self="@insert(content)">
</center>
<south height="50px" border="none">
<include src="/chapter3/footer.zul"/>
</south>
</borderlayout>
</zk>
- Line 9: Define an anchor with name content
Apply the Template
After creating a template zul, we can apply it in another zul with directive
<?init class="org.zkoss.zk.ui.util.Composition" arg0="template_path"?>
This directive tells ZK that this page uses the specified template. Then we also have to define zul fragments that are inserted to the anchor in the template zul with annotation @define(anchorName) at self attribute. The anchorName you specify should correspond to one of anchors defined in the template zul.
chapter7/pagebase/index.zul
<?link rel="stylesheet" type="text/css" href="/style.css"?>
<?init class="org.zkoss.zk.ui.util.Composition" arg0="/chapter7/pagebase/layout/template.zul"?>
<zk>
<include self="@define(content)" src="/chapter7/pagebase/home.zul"/>
</zk>
- Line 2: Tell ZK that we want to use a template zul for current page and give the path of template zul.
- Line 4: The anchor name content correspond to the anchor name defined in the template zul in previous section.
After above steps, when you visit http://localhost:8080/tutorial/chapter7/pagebase/index.zul, ZK will render the page based on template.zul and attach Include component to be the children of <center>.
Traditional web applications are usually designed as page-based navigation. Each function corresponds to a independent page with independent URL. It is very clear for users to know where they are from the URL and they can press "go back" button on their browser to go back to previous pages in history. But the drawback is users have to wait whole page reloading every time they switch to a function. Besides, developers also have to maintain multiple pages that have similar contents but applying a template zul can reduce this problem.
To build a page-based navigation, first you should prepare pages for those items in the sidebar.
From above image, you can see there are four zul pages under "chpater7\pagebase" (index-profile-mvc.zul, index-profile-mvvm.zul, index-todolist-mvc.zul, index-todolist-mvvm.zul) and each page corresponds to each item in the sidebar. Then we can link four items of the sidebar to these zul pages by redirecting a browser.
Next, we apply the template zul created before on those 4 pages.
/chapter7/pagebase/index-profile-mvc.zul
<?link rel="stylesheet" type="text/css" href="/style.css"?>
<?init class="org.zkoss.zk.ui.util.Composition" arg0="/chapter7/pagebase/layout/template.zul"?>
<zk>
<include self="@define(content)" src="/chapter5/profile-mvc.zul"/>
</zk>
- Line 2: Apply the template in /chapter7/pagebase/layout/template.zul.
- Line 4: Define a zul fragment for the anchor content.
Our example application creates those menu items dynamically upon a configuration, so we should initialize configuration.
Page-based navigation's sidebar configuration
public class SidebarPageConfigPagebaseImpl implements SidebarPageConfig{
HashMap<String,SidebarPage> pageMap = new LinkedHashMap<String,SidebarPage>();
public SidebarPageConfigPagebaseImpl(){
pageMap.put("zk",new SidebarPage("zk","www.zkoss.org","/imgs/site.png","http://www.zkoss.org/"));
pageMap.put("demo",new SidebarPage("demo","ZK Demo","/imgs/demo.png","http://www.zkoss.org/zkdemo"));
pageMap.put("devref",new SidebarPage("devref","ZK Developer Reference","/imgs/doc.png","http://books.zkoss.org/wiki/ZK_Developer's_Reference"));
pageMap.put("fn1",new SidebarPage("fn1","Profile (MVC)","/imgs/fn.png","/chapter7/pagebase/index-profile-mvc.zul"));
pageMap.put("fn2",new SidebarPage("fn2","Profile (MVVM)","/imgs/fn.png","/chapter7/pagebase/index-profile-mvvm.zul"));
pageMap.put("fn3",new SidebarPage("fn3","Todo List (MVC)","/imgs/fn.png","/chapter7/pagebase/index-todolist-mvc.zul"));
pageMap.put("fn4",new SidebarPage("fn4","Todo List (MVVM)","/imgs/fn.png","/chapter7/pagebase/index-todolist-mvvm.zul"));
}
...
}
- Line 9~12: Specify URL and related data for each menu item's configuration.
The following codes show how to redirect user to a independent page when they click a menu item in the sidebar.
Controller for page-based navigation
public class SidebarPagebaseController extends SelectorComposer<Component>{
...
//wire service
SidebarPageConfig pageConfig = new SidebarPageConfigPagebaseImpl();
@Override
public void doAfterCompose(Component comp) throws Exception{
super.doAfterCompose(comp);
//to initial view after view constructed.
Rows rows = fnList.getRows();
for(SidebarPage page:pageConfig.getPages()){
Row row = constructSidebarRow(page.getName(),page.getLabel(),page.getIconUri(),page.getUri());
rows.appendChild(row);
}
}
private Row constructSidebarRow(String name,String label, String imageSrc, final String locationUri) {
//construct component and hierarchy
Row row = new Row();
Image image = new Image(imageSrc);
Label lab = new Label(label);
row.appendChild(image);
row.appendChild(lab);
//set style attribute
row.setSclass("sidebar-fn");
EventListener<Event> actionListener = new SerializableEventListener<Event>() {
private static final long serialVersionUID = 1L;
public void onEvent(Event event) throws Exception {
//redirect current url to new location
Executions.getCurrent().sendRedirect(locationUri);
}
};
row.addEventListener(Events.ON_CLICK, actionListener);
return row;
}
}
- Line 15: Create menu items in the sidebar upon configurations with Rows.
- Line 39: Add a event listener to redirect a browser to the URL specified in the menu item a user clicks.
Visit http://localhost:8080/tutorial/chapter7/pagebase/index.zul. You will see the URL changes and whole page reloads when each time you click a different menu item.
A ZK page (Page) is a collection of components. Only those components attached to a page are available at the client and you can get a Page object by Component.getPage(). A desktop (Desktop) is a collection of ZK pages. Both a desktop and a ZK page are created automatically when ZK loads a zul page, and it won't re-create a new desktop until you reload the whole page. When you include another zul with Include, ZK will combine the parent zul and included zul as a whole ZK page.
When switching between different functions, you can see that only central area's content changes during switching. Other three areas (header, sidebar, and footer) remain still. But if your application is built in page-based navigation, a browser have to reload all contents no matter it changes or not during function switching. With AJAX's help, ZK allows you to implement another navigation way that only updates part of a page instead of reloading the whole page. By changing src attribute of Include component, we can change partial content of an page instead of redirecting to another page to achieve the navigation purpose. Because this navigation can be performed within a ZK desktop, we name it single desktop navigation. This navigation way response faster than page-based one for it only updates partially, but it doesn't change a browser's URL after switching to a different function. Hence, users cannot use "go back" button to return to previous page in the browser's history.
We will use the same layout to demonstrate the single desktop navigation.
Below is the index page, its content is nearly the same as the index page of page based example except it includes a different zul.
chapter7/single/index.zul
<?link rel="stylesheet" type="text/css" href="/style.css"?>
<?init class="org.zkoss.zk.ui.util.Composition" arg0="/chapter7/single/layout/template.zul"?>
<zk>
<include id="mainInclude" self="@define(content)" src="/chapter7/single/home.zul"/>
</zk>
- Line 4: We give the component id for we can find it later with ZK selector.
This navigation way is mainly implemented by changing src of Include component to switch between different zul pages so that it only reloads included components without affecting other areas . We still need to initialize sidebar configuration:
Single desktop navigation's sidebar configuration
public class SidebarPageConfigSingleDesktopImpl implements SidebarPageConfig{
HashMap<String,SidebarPage> pageMap = new LinkedHashMap<String,SidebarPage>();
public SidebarPageConfigSingleDesktopImpl(){
pageMap.put("zk",new SidebarPage("zk","www.zkoss.org","/imgs/site.png","http://www.zkoss.org/"));
pageMap.put("demo",new SidebarPage("demo","ZK Demo","/imgs/demo.png","http://www.zkoss.org/zkdemo"));
pageMap.put("devref",new SidebarPage("devref","ZK Developer Reference","/imgs/doc.png","http://books.zkoss.org/wiki/ZK_Developer's_Reference"));
pageMap.put("fn1",new SidebarPage("fn1","Profile (MVC)","/imgs/fn.png","/chapter5/profile-mvc.zul"));
pageMap.put("fn2",new SidebarPage("fn2","Profile (MVVM)","/imgs/fn.png","/chapter5/profile-mvvm.zul"));
pageMap.put("fn3",new SidebarPage("fn3","Todo List (MVC)","/imgs/fn.png","/chapter6/todolist-mvc.zul"));
pageMap.put("fn4",new SidebarPage("fn4","Todo List (MVVM)","/imgs/fn.png","/chapter6/todolist-mvvm.zul"));
}
...
}
- Line 9 ~ 12: Because we only need those pages that doesn't have header, sidebar, and footer, we can re-use those pages written in previous chapters.
In sidebar controller, we get the Include and change its src according to the menu item's URL.
Controller for single desktop navigation
public class SidebarSingleDesktopController extends SelectorComposer<Component>{
@Wire
Grid fnList;
//wire service
SidebarPageConfig pageConfig = new SidebarPageConfigSingleDesktopImpl();
@Override
public void doAfterCompose(Component comp) throws Exception{
super.doAfterCompose(comp);
//to initial view after view constructed.
Rows rows = fnList.getRows();
for(SidebarPage page:pageConfig.getPages()){
Row row = constructSidebarRow(page.getName(),page.getLabel(),page.getIconUri(),page.getUri());
rows.appendChild(row);
}
}
private Row constructSidebarRow(final String name,String label, String imageSrc, final String locationUri) {
//construct component and hierarchy
Row row = new Row();
Image image = new Image(imageSrc);
Label lab = new Label(label);
row.appendChild(image);
row.appendChild(lab);
//set style attribute
row.setSclass("sidebar-fn");
//new and register listener for events
EventListener<Event> onActionListener = new SerializableEventListener<Event>(){
private static final long serialVersionUID = 1L;
public void onEvent(Event event) throws Exception {
//redirect current url to new location
if(locationUri.startsWith("http")){
//open a new browser tab
Executions.getCurrent().sendRedirect(locationUri);
}else{
//use iterable to find the first include only
Include include = (Include)Selectors.iterable(fnList.getPage(), "#mainInclude").iterator().next();
include.setSrc(locationUri);
...
}
}
};
row.addEventListener(Events.ON_CLICK, onActionListener);
return row;
}
}
- Line 46: Since Include is not a child component of the component that SidebarSingleDesktopController applies to, we cannot use @Wire to retrieve it. Therefore, we use Selectors.iterable() to get components with the id selector from the page. Because ZK combines included components and its parent into one ZK page.
- Line 47: Change the src to corresponding URL that belongs to the clicked menu item.
Visit the http://localhost:8080/tutorial/chapter7/single/index.zul see the result.