Skip to content

Instantly share code, notes, and snippets.

@donmhico
Last active December 10, 2019 19:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save donmhico/564fe2ffa3ba919e2b7d8b782aff23d6 to your computer and use it in GitHub Desktop.
Save donmhico/564fe2ffa3ba919e2b7d8b782aff23d6 to your computer and use it in GitHub Desktop.
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