| | 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 | { |
| | 320 | if ( empty( $src ) ) |
| | 321 | return $html; |
| | 322 | |
| | 323 | $file = wp_check_filetype( $src ); |
| | 324 | if ( |
| | 325 | isset( $file['ext'] ) |
| | 326 | && ! in_array( $file['ext'], apply_filters( 'allowed_js_template_extensions', array( 'tmpl', ) ) ) |
| | 327 | ) |
| | 328 | return $html; |
| | 329 | |
| | 330 | $dom = new \DOMDocument; |
| | 331 | $dom->loadHTML( $html ); |
| | 332 | |
| | 333 | /** @var \DOMElement $tag */ |
| | 334 | foreach ( $dom->getElementsByTagName( 'script' ) as $tag ) |
| | 335 | { |
| | 336 | if ( $tag->hasAttribute( 'type' ) ) |
| | 337 | { |
| | 338 | $tag->setAttribute( 'type', 'text/template' ); |
| | 339 | $tag->setAttribute( 'id', $handle ); |
| | 340 | $tag->appendChild( $dom->createTextNode( file_get_contents( $src ) ) ); |
| | 341 | $tag->removeAttribute( 'src' ); |
| | 342 | $html = $dom->saveHTML( $tag ); |
| | 343 | } |
| | 344 | } |
| | 345 | |
| | 346 | return $html; |
| | 347 | } |