单独的模板文件不使用主干和下划线呈现

Roy*_*M J 7 backbone.js

通过使用

<script type="text/template" id="templateid">
<!-- Template content goes here -->
</script>
Run Code Online (Sandbox Code Playgroud)

代码效果很好.

但是,如果我把模板作为外部文件

<script type="text/template" id="templateid" src="template.js"></script>
Run Code Online (Sandbox Code Playgroud)

这不行.

以上两种方法有什么区别,我怎样才能解决这个问题?或者我错过了一些可能很明显的东西?

Roy*_*M J 24

尽管我接受了另一个答案,但我还是以几种不同的方式实现了这一特殊要求.我发布了我发现的最好和最简单的方法,我认为这对于那些不想使用任何模板引擎(如木偶等)的人有用.

使用Backbone和Underscore:

文件夹结构

文件夹Structure可以如下:

Root:
????css
????js
?   ????router.js
?   ????model.js
?   ????view.js
?   ????config.js   
????templates
?   ????home.html
?   ????login.html
?   ????register.html   
????images
????index.html
Run Code Online (Sandbox Code Playgroud)

基本模板

您需要有一个基本模板(index.html),您将在其中呈现不同的模板.这将确保每次呈现新页面时都不会加载诸如听众,页脚,导航菜单等常见的html内容,从而大大增加页面加载速度.

样本结构可以如下:

<html>
<head>
<!--Relevant CSS files-->
</head>
<body>
<div class="template_body">
    <div class="header">  
         <!--HTML content for header-->
    </div>
    <div class="content" id="template">
          <!--This would be where the dynamic content will be loaded-->
    </div>
    <div class="footer">
         <!--HTML content for footer-->
    </div>
</div>
<!--Include relevant JS Files-->
</body>
</html> 
Run Code Online (Sandbox Code Playgroud)

注意:请注意,您可以根据需要决定模板的结构.我正在使用的是一个更普遍的,所以每个人都可以轻松地与它相关.


视图

在您的视图中,您可以将特定模板呈现到基本模板,如下所示:

var LoginView = Backbone.View.extend({
    el: "#template",//Container div inside which we would be dynamically loading the templates
    initialize: function () {
        console.log('Login View Initialized');
    },
    render: function () {
        var that = this;
        //Fetching the template contents
        $.get('templates/login.html', function (data) {
            template = _.template(data, {});//Option to pass any dynamic values to template
            that.$el.html(template);//adding the template content to the main template.
        }, 'html');
    }
});

var loginView = new LoginView();
Run Code Online (Sandbox Code Playgroud)

请注意,el标记非常重要.

要传递值以进行查看,只需将其传递为:

var data_to_passed = "Hello";
$.get('templates/login.html', function (data) {
    template = _.template(data, { data_to_passed : data_to_passed }); //Option to pass any dynamic values to template
    that.$el.html(template); //adding the template content to the main template.
}, 'html');
Run Code Online (Sandbox Code Playgroud)

在模板中:

<%=data_to_passed;%>//Results in "Hello"
Run Code Online (Sandbox Code Playgroud)

您可以传递数组,对象甚至变量.

希望这有帮助.干杯

  • 我想你错过了上一个代码块中的%.应该是`<%= data_to_passed;%>` (2认同)

Jak*_*ski 10

如果您只是尝试使用类似于$("#templateid").html()各种示例的内容来获取模板文本,则仅当文本在<script>标记中实际内联时才会起作用.

通常,无法使用<script>标记获取远程文件的内容.

如果要加载外部模板,则必须使用代码显式获取内容(例如,使用$.get()带有文本插件的JQuery 或require.js).

以下是有关如何在Backbone上下文中获取外部模板的更多详细信息:

但要小心 - 过度使用此解决方案将导致许多其他请求获取模板,结果导致应用程序相当缓慢.通常,以通常的方式嵌入模板(在<script>标签中内联)更好的性能.