Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Reusable WP template for PHP and JS
<?php
function load_js_template(){
get_template_part( 'sample-template' );
}
add_action( 'wp_footer', 'load_js_template' );
function render_template( $template_name, $tmpl_data ) {
// "/" should not be present, but let's sanitize just in case
$template_name = str_replace( '/', '_', $template_name );
// You can construct your template name path - maybe all templates are in
// /templates/js/ and are prefixed with "tmpl"
$path = "{$template_name}.php";
if ( ( $path = locate_template( array( $path ) ) ) ) {
include $path;
}
}
function sample_output( $content ) {
ob_start();
render_template( 'sample-template', array( 'name' => 'John Doe', 'avatar' => get_avatar( get_current_user_id(), 50 ), 'date' => date( 'Y-m-d' ) ) );
return $content . ob_get_clean();
}
add_filter( 'the_content', 'sample_output' );
<?php
if ( isset( $tmpl_data ) ) {
$is_js_tmpl = false;
// Setup some defaults - just in case. If you're certain in your input you can ignore this
$defaults = array(
'avatar' => '',
'name' => '',
'date' => '',
);
$data = wp_parse_args( $tmpl_data, $defaults );
} else {
$is_js_tmpl = true;
// These are our placeholders for the JS template
$data = array(
'avatar' => '{{{data.avatar}}}',
'name' => '{{{data.name}}}',
'date' => '{{data.date}}',
);
}
?>
<?php if ( $is_js_tmpl ) : ?>
<script type="text/html" id="tmpl-sample-template">
<?php endif; ?>
<div class="this-is-awesome">
<p><?php echo $data['avatar']; ?> Hi, I am <?php echo $data['name']; ?> and today is <?php echo $data['date']; ?></p>
</div>
<?php if ( $is_js_tmpl ) : ?>
</script>
<?php endif; ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.