Hide WordPress block editor for pages with a specific page template

Recently I had the requirement in a project where I wanted to remove the block editor, only for pages that had a specific page template assigned.

In my case the page template was inside the templates folder of the theme and the filename was page-content-hub.php. This meant the page template had a slug of:

templates/page-content-hub.php

The following code, in my case added to the themes functions.php file meant the editor did not show on pages with that template assigned.

<?php
/**
 * Removes the block editor on the content hub template.
 *
 * @param bool  $use_block_editor Whether to use the block editor.
 * @param mixed $post             The post object.
 *
 * @return bool
 */
function hd_disable_block_editor_for_content_hub( $use_block_editor, $post ) {

	// get the page template slug for this post.
	$template = get_page_template_slug( $post->ID );

	// if the template slug matches the content hub template.
	if ( 'templates/page-content-hub.php' === $template ) {
		
		// disable the block editor.
		$use_block_editor = false;

	}

	return $use_block_editor;

}

add_filter( 'use_block_editor_for_post', 'hd_disable_block_editor_for_content_hub', 10, 2 );