Skip to content

Instantly share code, notes, and snippets.

@donmhico
Last active Dec 10, 2019
Embed
What would you like to do?
A better and cleaner way to render HTML with your JS - WebDevStudios
var display_posts_template_revised = wp.template( 'display-posts-revised' );
$.post( ajax_url, request, function( response ) {
response.data.forEach( function ( post ) {
$('#display_posts').append( display_posts_template_revised( post ) );
});
});
<script type="text/html" id="tmpl-display-posts-revised">
<div id="post-{{ data.ID }}" class="post">
<h3>{{ data.post_title }}</h3>
<div class="post_meta">
<span class="post_date">{{ data.post_date }}</span>
</div>
<p>{{{ data.post_content }}}</p>
</div>
</script>
$.post( ajaxurl, request, function( response ) {
var htmlOutput = '';
response.data.forEach( function( post ) {
htmlOutput += '<div id="post-' + post.ID + '" class="post">' +
'<h3>' + post.post_title + '</h3>' +
'<div class="post_meta">' +
'<span class="post_date">' + post.post_date + '</span>' +
'</div>' +
'<p>' + post.post_content + '</p>' +
'</div>';
});
$( '#display_posts' ).html( htmlOutput );
});
<?php
add_action( 'wp_footer', 'display_posts_template' );
function display_posts_template() {
?>
<script type="text/html" id="tmpl-display-posts">
<# _.forEach( data, function ( post ) { #>
<div id="post-{{ post.ID }}" class="post">
<h3>{{ post.post_title }}</h3>
<div class="post_meta">
<span class="post_date">{{ post.post_date }}</span>
</div>
<p>{{{ post.post_content }}}</p>
</div>
<# }) #>
</script>
<?php
}
var display_posts_template = wp.template( 'display-posts' );
$.post( ajaxurl, request, function ( response ) {
$( '#display_posts' ).html( display_posts_template( response.data ) );
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment