I found some interesting embeding JavaScript mix with HTML in WordPress php files, for instance:

<?php // Template for the Attachment Details two columns layout. ?>
<script type="text/html" id="tmpl-attachment-details-two-column">
    <div class="attachment-media-view {{ data.orientation }}">
        <h2 class="screen-reader-text"><?php _e( 'Attachment Preview' ); ?></h2>
        <div class="thumbnail thumbnail-{{ data.type }}">
            <# if ( data.uploading ) { #>
                <div class="media-progress-bar"><div></div></div>
            <# } else if ( data.sizes && data.sizes.large ) { #>
                <img class="details-image" src="{{ data.sizes.large.url }}" draggable="false" alt="" />
            <# } else if ( data.sizes && data.sizes.full ) { #>
                <img class="details-image" src="{{ data.sizes.full.url }}" draggable="false" alt="" />
            <# } else if ( -1 === jQuery.inArray( data.type, [ 'audio', 'video' ] ) ) { #>
                <img class="details-image icon" src="{{ data.icon }}" draggable="false" alt="" />
            <# } #>

Could you say pls, how and why this mix HTML with JS does work(HTML rendered)? Why Javascript is executed inside “<# #>”? Is it special syntax or what?

1 Answer
1

These are Underscore Templates, handled by the wp.template() JavaScript function (source here) which takes in a template ID corresponding to a <script type="text/html" id="tmpl-{template ID}"> element containing such code and compiles it into a function. This function can then be executed with the variables used in the template in order to produce a string of HTML.

For the template in the excerpt provided in the question, that call might look like this:

const template = wp.template( 'attachment-details-two-column' );
const markup = template( {
  orientation: 'landscape',
  type: 'image',
  uploading: false,
  sizes: {
    large: {
      url: 'http://placehold.jp/3d4070/ffffff/150x150.png'
    }
  }
} );

Where markup would now be a string containing (in part):

    <div class="attachment-media-view landscape">
        <h2 class="screen-reader-text">Attachment Preview</h2>
        <div class="thumbnail thumbnail-image">
            <img class="details-image" src="https://placehold.jp/3d4070/ffffff/150x150.png" draggable="false" alt="" />

wp.template() configures Underscores to use <# #> delimiters instead of the standard <% %> in order to avoid conflicts with some environments, where PHP versions prior to 7.0 may have been configured with the now deprecated asp_tags directive.

Leave a Reply

Your email address will not be published. Required fields are marked *