From 7944a641d136e6d0eb76a4e5f565bb93232d549f Mon Sep 17 00:00:00 2001
From: Kaiser Franz Josef <wecodemore@gmail.com>
Date: Sun, 15 Feb 2015 14:08:19 +0100
Subject: [PATCH] Register JavaScript templates using the WP Dependency API

---
 wp-includes/functions.wp-scripts.php | 53 ++++++++++++++++++++++++++++++++++++
 1 file changed, 53 insertions(+)

diff --git a/wp-includes/functions.wp-scripts.php b/wp-includes/functions.wp-scripts.php
index 9fd5d87..3c16a2b 100644
--- a/wp-includes/functions.wp-scripts.php
+++ b/wp-includes/functions.wp-scripts.php
@@ -293,3 +293,56 @@ function wp_script_add_data( $handle, $key, $value ){
 	global $wp_scripts;
 	return $wp_scripts->add_data( $handle, $key, $value );
 }
+
+
+add_filter( 'script_loader_tag', 'wp_script_template_filter', 10, 3 );
+/**
+ * Allow registering JavaScript/Underscore templates as script/WP_Dependency.
+ *
+ * The default file extension for JS templates is `.tmpl`.
+ * If you use a custom extension, add it using the `allowed_js_template_extensions` filter.
+ *
+ * Note: Creating a new node is 25% faster
+ * $tag->appendChild( $dom->createTextNode( file_get_contents( $src ) ) );
+ * than setting the node value
+ * $tag->nodeValue = esc_html( file_get_contents( $src ) );
+ * @link @link http://chat.stackexchange.com/transcript/message/19567599#19567599
+ *
+ * @since 4.2.0
+ *
+ * @param string $html
+ * @param string $handle
+ * @param string $src
+ * @return string
+ */
+function wp_script_template_filter( $html, $handle, $src ) {
+	if ( empty( $src ) )
+		return $html;
+
+	$file = wp_check_filetype( $src );
+
+	if ( ! isset( $file['ext'] ) )
+		return $html;
+
+	if ( ! in_array(
+		$file['ext'],
+		apply_filters( 'allowed_js_template_extensions', array( 'tmpl', ) )
+	) )
+		return $html;
+
+	$dom = new DOMDocument;
+	$dom->loadHTML( $html );
+
+	/** @var DOMElement $tag */
+	foreach ( $dom->getElementsByTagName( 'script' ) as $tag ) {
+		if ( $tag->hasAttribute( 'type' ) ) {
+			$tag->setAttribute( 'type', 'text/template' );
+			$tag->setAttribute( 'id', $handle );
+			$tag->appendChild( $dom->createTextNode( file_get_contents( $src ) ) );
+			$tag->removeAttribute( 'src' );
+			$html = $dom->saveHTML( $tag );
+		}
+	}
+
+	return $html;
+}
-- 
1.9.4.msysgit.1

