Direct View Model Overlay Value

You can directly add a specific ViewModel overlay key’s value to every View. The following example describes how to create a ViewModel overlay that inserts a permalink into each View. This example works best if you define a default URL for the site as described in Settings for the Global site or Creating sites.

Step 1: Create Model

You can use any new or existing Model with an overlay. No extra coding is required. For an example of a simple Model, see the snippet Simple content type with text and image fields.

Step 2: Create ViewModel Overlay

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
package content.article;

import com.psddev.cms.view.ViewModelOverlay;
import com.psddev.dari.db.State;
import com.psddev.dari.util.CompactMap;
import java.util.Map;
import java.util.function.Supplier;
import com.psddev.cms.db.Directory;

public class PermalinkViewModelOverlay implements ViewModelOverlay {

    @Override
    public Map<String, Supplier<Object>> create(Object model, String viewTemplate) {
        Map<String, Supplier<Object>> overlay = new CompactMap<>();
        overlay.put("fullPermalink",() -> State.getInstance(model).as(Directory.ObjectModification.class).getFullPermalink());
        return overlay;
    }
}

In the previous snippet—

  • Line 10 declares a class that implements ViewModelOverlay. Any class that implements this interface injects its key-value pairs into every View.
  • Line 14 creates a map of key-value pairs.
  • Line 15 retrieves the current page’s permalink, and assigns it to the key fullPermalink. (For this example to work you also need to configure the Default Site URL as explained in Settings for the Global site.) You can add any number of key-value pairs to the overlay.

Step 3: Create Data File

You can use any new or existing Styleguide data file. No extra coding is required. For an example of a simple data file, see the snippet Sample data file.

Step 4: Insert Overlay Key Into Template

Referring to the previous snippet in Step 2, you now have access to the key fullPermalink in every View by inserting that key as a placeholder in a Handlebars template. When rendering the View, Brightspot retrieves the value for the placeholder without your implementing a method in any ViewModel.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<html>
    <body>
        <div class="Article">
            <div class="Article-headline">
                <h1>{{headline}}</h1>
            </div>
            <div class="Article-body">
                {{body}}
            </div>
            <div class="Article-body">
                Permalink to this item: {{fullPermalink}}
            </div>
        </div>
    </body>
</html>

In the previous snippet, line 11 contains the placeholder for the key contained in the overlay.

../../../../_images/view-model-overlay-rendered.svg

See also: