Cert++
Close

Adding template data with getViewData and setViewData

Key Takeaway

In an SFRA middleware step, read the view data with res.getViewData(), add your new property to that object, write it back with res.setViewData(), and then call next().

In SFRA, a controller route builds a view data object that holds the data an ISML template or JSON response will use. res.getViewData() reads that object. res.setViewData() updates it. With these two methods, any middleware step can add data for rendering without repeating the original controller's logic, including a step that a custom cartridge adds.

View data and the pdict

res.render(templateName, data) outputs the template and assigns data to the pdict. When you pass a model in for rendering, the model is assigned to the viewData variable.

Two methods on the response object work with the view data. res.getViewData() returns the current viewData object from the response object. res.setViewData(data) updates the viewData object used for rendering. Unlike res.render() or res.json(), res.setViewData() doesn't render anything by itself.

res.setViewData() merges all the data you pass into a single object, so you can call it at every step of the middleware chain.

A route has several middleware steps. One separate middleware function looks up the user's locale, for example French, and adds it to the view data with res.setViewData(). When the page renders, it has the locale available, so it can show a language switch.

B2C Commerce Developer Study Guide

Checklist progress

0/237Learned

Given a requirement, create and extend the functionality of a JavaScript controller that leverages models, decorators, factories, or helpers following API best practices, and renders a template or returns a JSON response

0/11

Prepare for the Exam

Play Today's Certle

Study Community

Ask questions and get the latest info from other B2C Commerce Developer studiers.