Using Underscore Templates in WordPress

I’ve noticed that since WP 3.5 that we now have the Backbone.js and Underscore.js libraries included. The new Media Modal uses Underscore templates and I was wondering how would I be able to insert them, especially in the admin side of things.Is there a correct way to insert these?

Related posts

Leave a Reply

1 comment

  1. Your plugin index file:

    add_action( 'print_media_templates', 'wpse8170_admin_footer' );
    function wpse8170_admin_footer() {
    
        require 'templates.php';
    }
    

    Your templates.php:

    <script id="tmpl-mytemplate" type="text/html">
        <h1>Hello {{data.name}}!</h1>
    </script>
    

    Your media js file:

    wp.media.view.MyView = wp.media.View.extend({
        template: wp.media.template('mytemplate'),
    
        render: function() {
            this.$el.html(this.template({name: 'world'}));
        }
    });