Skip to content

Instantly share code, notes, and snippets.

@weskoop
Last active August 29, 2015 14:15
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save weskoop/2f69e69aefdadda7c94d to your computer and use it in GitHub Desktop.
PHP Wrapper to emulate wp.template using mustache.php
<?php
/**
* wp.template.php
*
* PHP Wrapper to emulate wp.template using mustache.php
*
* mustache.php: https://github.com/bobthecow/mustache.php
*
* JS Example
*
singleTemplate = wp.template( 'template-part' );
var output = singleTemplate( { foo: 'bar' } );
*
* PHP Example
*
$singleTemplate = wp_template( 'template-part' );
$output = $singleTemplate( array( 'foo' => 'bar' ) );
*
* @author Wes Koopmans, Of Desks <inc@ofdesks.com>
* @license GPL-2.0+
* @link http://ofdesks.com
* @copyright 2014 Of Desks Studio Inc.
* @version 0.1
*/
class WP_Template {
// Our Template
private $template;
// Our Processor
private $mustache;
/**
* Setup Mustache, etc.
*
* @param [type] $template
* @param array $settings
*/
function __construct( $template, $settings = array() ) {
// Autoloader
if ( !class_exists( 'Mustache_Autoloader' ) ) {
require_once 'Mustache/Autoloader.php';
Mustache_Autoloader::register();
}
$this->mustache = new Mustache_Engine( $settings );
// Load in Template
$this->template = $template;
}
/**
* Wrapper Returner
*
* Send back a wrapper for the render function.
* We're always going to assign all of the data
* to $data so that we emulate the wp.template
* way of doing {{data.xxxx}}
*
* @return function
*/
public function wp_template() {
return function( $data = '' ) {
return $this->render( array('data' => $data ) );
};
}
/**
* Simple function to render Templates
*
* @param array $data
* @return string
*/
public function render( $data = array() ) {
return $this->mustache->render( $this->template, (object) $data );;
}
}
/**
* wp.template emulator!
*
* Redeclare it and change functionality if you need too.
* ( Maybe you want a templates folder, maybe it's plugin not theme, etc. )
*
* @param string $template valid slug for get_template_part( 'tmpl', $template )
* @return function
*/
if ( !function_exists( 'wp_template' ) ) :
function wp_template( $template_part, $settings = array() ) {
ob_start();
get_template_part( 'tmpl', $template_part );
$template = ob_get_contents();
ob_end_clean();
$wp_template = new WP_Template( $template, $settings );
return $wp_template->wp_template();
}
endif;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment