1

I have a Drupal 8 site that is using a bunch of custom views with REST endpoints. These views contain a bunch of content nodes on them which make up a single page.

I have been able to generate an XML sitemap of the views by using Simple XML Sitemap module but I am wanting to know if (and how) it's possible to generate a JSON sitemap of all the views and the paths that are associated with REST but dynamically?

1
  • How would that JSON sitemap look like, basically? Please update your question to add sample output.
    – leymannx
    Mar 12, 2019 at 6:58

1 Answer 1

2

Create a simple custom REST resource in a custom module and within the resource you can return a list of views and other relevant information

Here is a get() function that returns views that are enabled and their displays

/**
 * Responds to entity GET requests.
 * @return \Drupal\rest\ResourceResponse
 */
public function get() {

    $entity_ids = \Drupal::service('entity.query')
        ->get('view')
        ->condition('status', TRUE)
        ->execute();

    $views = [];        
    foreach (\Drupal::entityManager()
        ->getStorage('view')
        ->loadMultiple($entity_ids) as $view) {

        $displays = [];
        // Check each display to see if it meets the criteria and is enabled.
        foreach ($view->get('display') as $id => $display) {

            // If the key doesn't exist, enabled is assumed.
            $enabled = !empty($display['display_options']['enabled']) || !array_key_exists('enabled', $display['display_options']);
            if ($enabled ) {
                $displays[] = [
                    'id' => $display['id'],
                ];
            }
        }
        $views[] = [
            'view_id' => $view->id(),
            'displays' => $displays,
        ];
    }

    $response = new ResourceResponse($views);
    return $response;
}

You can modify the views array using the for loops to display any information that you find relevant to your task.

Here is a working demo module that I did for the sake of this exercise

1
  • Perfect. Thank you Mar 12, 2019 at 23:33

Not the answer you're looking for? Browse other questions tagged or ask your own question.