8

通过使用

<script type="text/template" id="templateid">
<!-- Template content goes here -->
</script>

代码运行良好。

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

<script type="text/template" id="templateid" src="template.js"></script>

这行不通。

上述两种方法有什么区别,我该如何解决这个问题?还是我在这里遗漏了一些可能很明显的东西?

4

2 回答 2

24

即使我接受了另一个答案,我还是继续以几种不同的方式实现了这个特定的要求。我发布了我发现的最好和最简单的方法,我认为这对不想使用任何模板引擎(如木偶等)的人很有用。

使用主干和下划线:

文件夹结构

文件夹结构可以如下:

Root:
├───css
├───js
│   ├───router.js
│   ├───model.js
│   ├───view.js
│   └───config.js   
├───templates
│   ├───home.html
│   ├───login.html
│   └───register.html   
└───images
└───index.html

基本模板

您将需要一个基本模板(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> 

注意:请注意,您可以根据需要决定模板的结构。我使用的是更通用的,以便每个人都可以轻松地与之相关。


看法

在您看来,您可以将特定模板渲染到基本模板,如下所示:

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

请注意,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');

在模板中:

<%=data_to_passed;%>//Results in "Hello"

您可以传递数组、对象甚至变量。

希望这对您有所帮助。干杯

于 2013-12-20T05:52:42.317 回答
10

如果您只是尝试通过使用$("#templateid").html()来自各种示例的类似内容来获取模板文本,那么只有当文本真正内联在<script>标签中时,这才有效。

<script>一般来说,使用标签是不可能获取远程文件的内容的。

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

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

但是要小心 - 过度使用此解决方案将导致大量额外的获取模板的请求,从而导致应用程序相当缓慢。通常,以通常的方式嵌入模板(<script>标签内联)会更好地提高性能。

于 2013-06-26T09:37:36.030 回答