Last Updated: February 25, 2016
·
905
· pimschaaf

Use WordPress is_page_template() in JavaScript

To use is_page_template() in JavaScript I do the following in a function hooked to wp_enqueue_scripts:

Enqueue JavaScript file, make is_page() and the current page_template available in a variable through wp_localize_script()

/* Functions.php */ 
function enqueue_scripts() {
      wp_enqueue_script('main-js', get_template_directory_uri() . '/assets/js/main.js', array('jquery'), '1.0');

      $data = array(
        'is_page'   => is_page(),
        'page_template' => get_page_template_slug( get_queried_object_id() ),
    );

      wp_localize_script('main-js', 'site_data', $data);
}
add_action('wp_enqueue_scripts', 'enqueue_scripts');

In the main.js file, add the function that mimics the WordPress is_page_template function.

/* main.js */
function is_page_template(string) {
    if (string && site_data.is_page) {
        return site_data.page_template === string;
    }
    return false;
}