Skip to content

Commit 72dbca3

Browse files
author
Andrew
committed
add inline template getters - JSONP with optional callbacks and single templates
1 parent 131e2a8 commit 72dbca3

File tree

1 file changed

+31
-2
lines changed

1 file changed

+31
-2
lines changed

mustache.php

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,33 @@ function element( $element, $values = array() ) {
6666
return $result;
6767
}
6868

69+
/** Return the JSON encoded template and sub-templates with an optional
70+
* callback. Used to put the templates directly into a script tag
71+
*
72+
* @param type $template
73+
* @param type $callback
74+
* @return type
75+
*/
76+
function getJSONPTemplates( $element, $callback = false ) {
77+
$template = $this->_loadTemplate( $element );
78+
$this->partials[ $element ] = $template; //make sure everything comes back
79+
if( $callback ) {
80+
return sprintf('%s(%s);', $callback, json_encode( $this->partials ) );
81+
} else {
82+
return json_encode( $this->partials );
83+
}
84+
}
85+
86+
/** Get the text of a single template. Public wrapper for _loadtemplate.
87+
* Does NOT get sub templates
88+
*
89+
* @param type $element
90+
* @return type
91+
*/
92+
function getSingleTemplate( $element ) {
93+
return $this->_loadTemplate( $element, false );
94+
}
95+
6996

7097
/** Get the path to an element file. Will have the extension provided above
7198
* Ensures we are getting a .mustache file from the elements directory
@@ -84,7 +111,7 @@ private function _getElementPath( $element ) {
84111
* @param string - $element relative path from the elements folder
85112
* @return string - template string for rendering with Mustache
86113
*/
87-
private function _loadTemplate( $element ) {
114+
private function _loadTemplate( $element, $load_sub_templates = true ) {
88115
$path = $this->_getElementPath( $element );
89116

90117
//fail nicely if we have a bad file
@@ -98,7 +125,9 @@ private function _loadTemplate( $element ) {
98125
$template = fread( $template_file, filesize( $path ) );
99126

100127
//load any partials
101-
$this->_loadPartials( $template );
128+
if( $load_sub_templates ) {
129+
$this->_loadPartials( $template );
130+
}
102131
return $template;
103132
}
104133

0 commit comments

Comments
 (0)