Sharing templates with the JSON API?

You can use wp_localize_script();:

// Example:
wp_register_script( 'your-template-script', $path, $dependencies, $version, true );
wp_enqueue_script( 'your-template-script' );
wp_localize_script( 
     'your-template-script' 
    ,'your_template_object'
    ,array( 
         'ajaxurl'          => admin_url( 'admin-ajax.php' )
        ,'template_nonce'   => wp_create_nonce( self :: $search_nonce_val ) 
        ,'action'           => 'build_template'
        ,'title'            => get_the_title()
        ,'content'          => get_the_content()
        ,'title_format'         => 'h1'
     ) 
);

Then you can use it in your template.js file like the following:

function onAJAXSuccess( target_id, obj ) { // calling this on ajax.success 
    var 
        title = obj.title
        content = obj.content
        string = '<'+obj.title_format+'>'+title+'</'+obj.title_format+'>'+content;
    ;

    jQuery( '#' + target_id ).html( string ).fadeIn();
}

Then call it like this: onAJAXSuccess( 'template_container_id', your_template_object );.

Leave a Comment