Sitevision Developer
Log in

Log in

Pre render hooks in WebApps

Sitevision 6.2 introduces a new WebApp feature that enables code execution before page rendering starts.

Published: 2020-03-11  |  Updated: 2024-09-24

What is a pre render hook?

Pre render hooks are functions that let you run code before Sitevision starts rendering a page. Hooks belong to a WebApp and have full access to Sitevision's Public API as well as WebApp specific utilities.

What hooks are available?

Sitevision offers three types of hooks:

  • beforeRender
    Intended to run arbitrary code.
  • getPageTitle
    Return a title that will be used for the current page.
  • addHeadElement
    Add an element to the <head> section of the current page.

A use case

A typical use case would be a WebApp displaying something based on a parameter. In such case it would be nice to alter the page title depending on what is shown and add open graph meta tags to describe your content. Below is an example of how this would be achieved using pre render hooks.

// hooks.js
(function() {
   'use strict';

   const { beforeRender, addHeadElement, getPageTitle } = require('hooks');
   const { getEventData } = require('/module/server/eventsApi');
   const { escape } = require('underscore');

   beforeRender((req) => {
      const data = getEventData(req.params.eventId);

      req.context.eventData = data; // req.context is propagated to the rendering phase (index.js)
   });

   getPageTitle((req) => req.context.eventData.title);

   addHeadElement((req) => {
      const description = escape(req.context.eventData.description);

      return '<meta property="og:description" content="' + description + '">';
   });
   
   addHeadElement((req) => {
      const image = escape(req.context.eventData.image);

      return '<meta property="og:image" content="' + image + '">';
   });
}());

Documentation

Refer to the pre render hooks documentation for more information.