gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 14:03:35 24 4
gpt4 key购买 nike

我是 backbone.js 的新手,我正在练习在我的“index.html”页面中显示模板。我在“index.html”中创建了一个模板并在使用 View 中显示它。它适用于单个 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>

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

 <div class="tags" id="myTags">  </div><!--/tags--> 

下面是 View 脚本(在同一个文件“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>

因此,请建议我进行更改以使此模板成为外部模板。提前谢谢。 . .

最佳答案

最简单的方法是使用 backbone.js 本身建议的 underscore.js。如果您想更上一层楼,那么您可以选择模板引擎,例如:

  1. Handlebars
  2. Marionette

还有很多其他的..

我个人更喜欢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');

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

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');

}

});

App.baseUrl - 我设置为配置的项目根目录的完整路径。您可以重新使用它或删除它。但请确保您指向的是确切的模板文件夹。

您需要指定您的 el 标签,否则您需要硬编码您关注的 div 以呈现模板。

干杯

关于javascript - 如何使用 Backbone.js 在 html 页面中创建和显示外部模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19905406/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com