Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

up vote 1 down vote accepted

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 );.

share|improve this answer
1  
that's a sophisticated process! –  djb Feb 6 '12 at 14:51

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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