如何使用Backbone.js在html页面中创建和显示外部模板?

sac*_*are 2 html javascript jquery backbone.js

我是backbone.js的新手,我正在练习在我的'index.html'页面中显示模板.我已经在'index.html'中创建了一个模板并在一个使用视图中显示它.它可以在单个html文件中正常工作,即一切都保存在'index.html'中.但是现在我希望这些模板存储在其他文件中显示在我的'index.html'中.我试图找到一些解决方案,但都令人困惑.所以请,任何人都可以告诉我该怎么做.

以下是我要显示的模板(目前在'index.html'中):

<script type="text/template" id="cloudtag_tempalte">
     <center>
        <ul class="cld" ">
            <li   >     <a  class="tag1" id="t1"  href="https://www.google.com" target="_blank"></a>  </li> 
            <li  >      <a  class="tag2" id="t2"  href="#">sachin </a>     </li>
            <li  >      <a class="tag3"  id="t3"  href="#">Ramesh </a>     </li>
            <li  >      <a  class="tag1"id="t33" href="#">Tendulkar</a></li>
            <li  >      <a  class="tag5"id="t34" href="#">Cricket</a></li>
            <li  >      <a  class="tag2"id="t35" href="#">Test</a></li>
        </ul><!--/cld-->
     </center>
</script>   
Run Code Online (Sandbox Code Playgroud)

以下是显示它的div(在'index.html'中):

 <div class="tags" id="myTags">  </div><!--/tags--> 
Run Code Online (Sandbox Code Playgroud)

以下是视图脚本(在同一文件'index.html'中):

<script type="text/javascript">
var cld_view=Backbone.View.extend({
        initialize: function(){

        },
        render: function(){
            // Compile the template using underscore
            var template = _.template( $("#cloudtag_tempalte").html(), {} );
            // Load the compiled HTML into the Backbone "el"
            this.$el.html( template );

        }

    });

    var cloudtag=new cld_view({el:$("#myTags")});
    cloudtag.render();
</script>
Run Code Online (Sandbox Code Playgroud)

所以,请建议我进行更改以使此模板外部.坦克斯在普罗旺斯...

Roy*_*M J 8

最简单的方法是使用underscore.jsbackbone.js本身建议的方法.如果你想更高一点,那么你可以去模拟引擎,如:

  1. 把手
  2. 木偶

还有很多其他..

我个人更喜欢Underscore .js.一个例子如下:

使用下划线:

   $.get('templates/your-template-file.html', function (data) {
        template = _.template(data, {
             data: data_you_want_to_pass_to_template
        });
        this.$el.html(template);  
    }, 'html');
Run Code Online (Sandbox Code Playgroud)

至于将其扩展到您的代码:

var cld_view=Backbone.View.extend({
    el:'template_div',
    initialize: function(){

    },
    render: function(){
        // Compile the external template file using underscore
        $.get(App.baseUrl + 'templates/your-template-file.html', function (data) {
            template = _.template(data, {  });
            this.$el.html(template);  
        }, 'html');

    }

});
Run Code Online (Sandbox Code Playgroud)

App.baseUrl - 我的项目根目录的完整路径,设置为config.您可以重新使用此功能或将其删除.但只需确保,您指向确切的模板文件夹.

您需要指定el标记,否则您需要对要重点渲染模板的div进行硬编码.

干杯