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?
You can use
wp_localize_script();
:Then you can use it in your template.js file like the following:
Then call it like this:
onAJAXSuccess( 'template_container_id', your_template_object );
.