23 November 2023

Programmatically rendering a view in Drupal involves a structured series of steps. Initially, the target view is loaded using the views_get_view() function, specifying its machine name and the desired display variant through the set_display() method. Optional alterations to the view can be made programmatically, adjusting settings such as the number of items per page or contextual arguments. Subsequently, the pre_execute() method is invoked on the view object to prepare it for execution, allowing for any last-minute adjustments. The actual execution of the view is triggered with the execute() method, retrieving data based on the configured parameters. The final step involves calling the render() method to obtain the rendered output of the view in HTML format. This rendered output, stored in a variable like $output, can then be utilized within the Drupal application as needed. This process provides a dynamic and programmatic way to incorporate views into the display logic of a Drupal site, enabling flexibility and customization in response to specific requirements.

Source code viewer
  1. // Load and execute the view.
  2. $view = views_get_view('your_view_name');
  3. $view->set_display('default');
  5. $view->pre_execute();
  6. $view->execute();
  8. // Render the view.
  9. $output = $view->render();
Programming Language: PHP