Created
September 4, 2014 22:54
-
-
Save nikolov-tmw/8059ca8f1f5e0678be49 to your computer and use it in GitHub Desktop.
Reusable WP template for PHP and JS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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' ); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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