Vaadin 14: Using a Placeholder in RouterLayouts

Route offers the possibility to put the content of a View into a parent layout. By default, the content of the View is just appended to the parent layout. By using a placeholder, we can easily control where the content of the View is added.

import com.vaadin.flow.component.HasElement;
import com.vaadin.flow.component.Text;
import com.vaadin.flow.component.html.Div;
import com.vaadin.flow.router.RouterLayout;

import java.util.Objects;

public class MainLayout extends Div implements RouterLayout {

    /*
     * Define a simple empty Element, which is later used to find the injection point:
     */
    private Text contentPlaceholder = new Text("");

    public MainLayout() {
        add(new Text("my header"));
        /*
         * Place the placeholder at the intended position, e.g. between other blocks:
         */
        add(contentPlaceholder);
        add(new Text("my footer"));
    }

    @Override
    public void showRouterLayoutContent(HasElement content) {
        if (content != null) {
            getElement().insertChild(
                    /*
                     * Get the position of the placeholder inside the dom:
                     */
                    getElement().indexOfChild(contentPlaceholder.getElement()),
                    /*
                     * And insert the content of the View directly afterwards:
                     */
                    Objects.requireNonNull(content.getElement()));
        }
    }
}

Simply override the default showRouterLayoutContent method with a method which inserts the content directly after the placeholder.

Leave a Reply

Your email address will not be published. Required fields are marked *