Test your website performance for free
Test your website performance

Creating a Nested Widget

Creating a Nested Widget

When dealing with content, widgets, e.g. for text, images, Google maps, etc, come in handy. Add as many of them to your pages as you think appropriate, move them around, or edit their content.

In contrast to widgets containing and presenting their content directly, nested widgets are supposed to group other widgets together in order to make them function as a whole, or to simply arrange them nicely on the page. A tab group widget, for example, forms a tab group from the tab widgets you add to it.

Implementing a tab group widget

We will create a tab group widget consisting of tabs which are also represented as widgets. Every tab widget will have a title, which should be displayed as the tab title, and content that is displayed as the contents of the tab group if the tab is active. The content of a tab widget will be editable directly on the page. Adding, deleting, sorting and renaming tabs will be made available through the details dialog.

Here is what it should look like:

First, we'll have Scrivito generate the corresponding widget models:

The next step is to define the attributes the models require. We're going to provide two empty tabs for a new tab group by specifying them as the default of the “tabs” attribute. 

Also, we'll bind these widget types to one another to ensure that only tab widgets can be inserted into a tab group widget and, vice versa, that tab widgets may only be inserted into a tab group. The latter prevents tab widgets from being added directly to pages.

Next, we'll add the desired functionality to the widget views. The “show” view of the tab group widget should display its tabs and allow the user to edit their titles as well as the content of the active tab. Since the individual tab widgets are rendered by the template of the tab group widget, the tab widget template, “app/views/tab_widget/show.html.erb” should be removed.

We'll have the “details” view of the tab group widget display the tab widgets so that editors can rearrange tabs or delete them as needed:

The details views of the tab widgets makes their titles editable:

Look and feel

To make our tab group look and feel like a real tab group, please copy and paste some CSS and JavaScript code to the project.

Show CSS and JavaScript

Using the tab group widget

Now, navigate to a page that includes a widgetlist field and insert a tab group widget. The new tab group will be created with two tabs:

In the details dialog of the tab group widget you can rename existing tabs, change their order, delete or add a new tab:

You can, of course, edit the bodies of the tabs: