Sharing templates with the JSON API?

Is there any way to share ‘templates’ between JS and WordPress?

For instance, this sort of modest seat-of-the-pants templating feels ok:

var AJAXSuccessFunc = function(data){ // calling this on ajax.success 
    var title = data.page.title;
    var content = data.page.content;
    var string = '<h1>' + title + '</h1>' + content;
    targetDiv.html(string).fadeIn(); 
}

But given that content might appear in this manner, or via conventional WordPress PHP templates, it’s a bit worrying that I might have to maintain two basically identical templates for JS and PHP. Especially when there are more than a few HTML tags present.

I want to standardise and centralise everything! What are my options?

1 Answer
1

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