| 296 | |
| 297 | |
| 298 | add_filter( 'script_loader_tag', 'wp_script_template_filter', 10, 3 ); |
| 299 | /** |
| 300 | * Allow registering JavaScript/Underscore templates as script/WP_Dependency. |
| 301 | * |
| 302 | * The default file extension for JS templates is `.tmpl`. |
| 303 | * If you use a custom extension, add it using the `allowed_js_template_extensions` filter. |
| 304 | * |
| 305 | * Note: Creating a new node is 25% faster |
| 306 | * $tag->appendChild( $dom->createTextNode( file_get_contents( $src ) ) ); |
| 307 | * than setting the node value |
| 308 | * $tag->nodeValue = esc_html( file_get_contents( $src ) ); |
| 309 | * @link @link http://chat.stackexchange.com/transcript/message/19567599#19567599 |
| 310 | * |
| 311 | * @since 4.2.0 |
| 312 | * |
| 313 | * @param string $html |
| 314 | * @param string $handle |
| 315 | * @param string $src |
| 316 | * @return string |
| 317 | */ |
| 318 | function wp_script_template_filter( $html, $handle, $src ) { |
| 319 | if ( empty( $src ) ) |
| 320 | return $html; |
| 321 | |
| 322 | $file = wp_check_filetype( $src ); |
| 323 | |
| 324 | if ( ! isset( $file['ext'] ) ) |
| 325 | return $html; |
| 326 | |
| 327 | if ( ! in_array( |
| 328 | $file['ext'], |
| 329 | apply_filters( 'allowed_js_template_extensions', array( 'tmpl', ) ) |
| 330 | ) ) |
| 331 | return $html; |
| 332 | |
| 333 | $dom = new DOMDocument; |
| 334 | $dom->loadHTML( $html ); |
| 335 | |
| 336 | /** @var DOMElement $tag */ |
| 337 | foreach ( $dom->getElementsByTagName( 'script' ) as $tag ) { |
| 338 | if ( $tag->hasAttribute( 'type' ) ) { |
| 339 | $tag->setAttribute( 'type', 'text/template' ); |
| 340 | $tag->setAttribute( 'id', $handle ); |
| 341 | $tag->appendChild( $dom->createTextNode( file_get_contents( $src ) ) ); |
| 342 | $tag->removeAttribute( 'src' ); |
| 343 | $html = $dom->saveHTML( $tag ); |
| 344 | } |
| 345 | } |
| 346 | |
| 347 | return $html; |
| 348 | } |