Search code examples
javascripthtmltemplatesbackbone.jsunderscore.js

How to combine many templates into one html in the underscore, text


I have many templates in a tpl folder. To speed up the loading performance and reduce the interaction with the server, I want to combine the templates in one HTML with Id tag:

For example:

The following is the content of the template common.html

+++++++++++++++++++++++++++++++++++++++++++++++
<script type="text/template" id="tpl-banner1">
    <div class="banner">
        <div class="banWp addWrap" id="bannerWp1">
        </div>
    </div>
</script>
<script type="text/template" id="tpl-banner2">
    <div class="banner">
        <div class="banWp addWrap" id="bannerWp2">
        </div>
    </div>
</script>

+++++++++++++++++++++++++++++++++++++++++++++++

Two sections in the one html file. In the js, I just refer the template by:

define(['text!common.html'], function (IndexBannerTpl)  {

}

My question is how to refer the section (id="tpl-banner2")? in the backbone?

If only contains one section, I could use it like that:
+++++++++++++++++++++++++++++++++++++++++++++++
var template = _.template(IndexBannerTpl, {items: items_ibm});
+++++++++++++++++++++++++++++++++++++++++++++++

How to use id="tpl-banner1" and id="tpl-banner2"?

Sean WANG


Solution

  • Try the following:

    var html = $(IndexBannerTpl).filter('#tpl-banner1').html();
    var template = _.template(html, {items: items_ibm});