简体   繁体   English

jQuery的模板-导入文件?

[英]jquery templating - import a file?

I'm working with backbone.js, but as far as I've seen, it doesn't care what templating system you use. 我正在使用bone.js,但据我所知,它并不关心您使用的模板系统。 Currently I'm trying out mustache.js, but I'm open to other ones. 目前,我正在尝试mustache.js,但我对其他人开放。 I'm a little annoyed though with the way I have to put a template into a string: 我对将模板放入字符串中的方式感到有些恼火:

var context = {
    name: this.model.get('name'),
    email: this.model.get('email')
}

var template = "<form>Name<input name='name' type='text' value='{{name}}' />Email<input name='email' type='text' value='{{email}}' /></form>";

var html = Mustache.to_html(template, context);
    $(this.el).html(html);
    $('#app').html(this.el);

I'd like if I could load it from a different file or something somehow. 我想是否可以从其他文件或以某种方式加载它。 I want to be able to have template files in order to simplify things. 我希望能够拥有模板文件以简化操作。 For example, if I put it all in a string, I can't have breaks (well I can have html breaks, but that's not the point). 例如,如果我将所有内容都放在一个字符串中,则不会有中断(当然,我可以有html中断,但这不是重点)。 After the line starts to get very long, it becomes unmanageable. 该行开始变得很长之后,它变得难以管理。

Tips? 提示?

Updated (4/11/14): 更新(14/11/14):

As answered by OP below: 如以下OP所述:

Unfortunately, the jQuery team has moved the templating functionality out of jQuery Core. 不幸的是,jQuery团队已将模板功能从jQuery Core中移出。 The code is still available as a library here: github.com/BorisMoore/jquery-tmpl and here: github.com/borismoore/jsrender 该代码仍可在以下位置以库的形式获取: github.com/BorisMoore/jquery-tmpl和此处: github.com/borismoore/jsrender

Original Answer: 原始答案:

I just used this a couple of hours ago: http://api.jquery.com/category/plugins/templates/ 我是在几个小时前使用的: http : //api.jquery.com/category/plugins/templates/

It's an official jQuery plugin(ie the devs endorse it). 这是一个官方的jQuery插件(即开发人员认可的插件)。

This is the function you need to use for loading templates from things other than strings: http://api.jquery.com/template/ 这是从字符串以外的其他东西加载模板时需要使用的功能: http : //api.jquery.com/template/

Here's the code to have a template in HTML: 这是在HTML中具有模板的代码:

<script id="titleTemplate" type="text/x-jquery-tmpl">
  <li>${Name}</li>
</script>
___________

// Compile the inline template as a named template
$( "#titleTemplate" ).template( "summaryTemplate" );

function renderList() {
  // Render the movies data using the named template: "summaryTemplate"
  $.tmpl( "summaryTemplate", movies ).appendTo( "#moviesList" );
}

It's in a <script> tag, because that's not visible by default. 它在<script>标记中,因为默认情况下不可见。
Note the type="text/x-jquery-tmpl". 注意type =“ text / x-jquery-tmpl”。 If you omit that, it will try to parse it as JavaScript(and fail horribly). 如果您忽略了它,它将尝试将其解析为JavaScript(并严重失败)。

Also note that "loading from a different file" is essentially the same as "reading a file" and then "loading from a string". 另请注意,“从其他文件加载”与“读取文件”然后“从字符串加载”基本上相同。

Edit 编辑

I just found this jQuery plugin - http://markdalgleish.com/projects/tmpload/ Does exactly what you want, and can be coupled with $.tmpl 我刚刚发现这个jQuery插件- http://markdalgleish.com/projects/tmpload/不正是你想要什么,并能与连接$.tmpl


I have built a lightweight template manager that loads templates via Ajax, which allows you to separate the templates into more manageable modules. 我已经构建了一个轻量级的模板管理器,该管理器通过Ajax加载模板,使您可以将模板分为更易于管理的模块。 It also performs simple, in-memory caching to prevent unnecessary HTTP requests. 它还执行简单的内存中缓存,以防止不必要的HTTP请求。 (I have used jQuery.ajax here for brevity) (为了简洁起见,我在这里使用了jQuery.ajax)

var TEMPLATES = {};

var Template = {

  load: function(url, fn) {
    if(!TEMPLATES.hasOwnProperty(url)) {
      $.ajax({
        url: url,
        success: function(data) {
          TEMPLATES[url] = data;
          fn(data);
        }
      });
    } else {
      fn(TEMPLATES[url]);
    }
  },

  render: function(tmpl, context) {
    // Apply context to template string here
    // using library such as underscore.js or mustache.js
  }

};

You would then use this code as follows, handling the template data via callback: 然后,您将使用以下代码,通过回调处理模板数据:

Template.load('/path/to/template/file', function(tmpl) {
  var output = Template.render(tmpl, { 'myVar': 'some value' });
});

We are using jqote2 with backbone because it's faster than jQuery's, as you say there are many :) 我们将jqote2与主干一起使用,因为它比jQuery的快,就像您说的很多:)

We have all our templates in a single tpl file, we bind to our template_rendered so we can add jquery events etc etc 我们将所有模板都放在一个tpl文件中,我们绑定到template_rendered,因此我们可以添加jquery事件等

App.Helpers.Templates = function() {

  var loaded = false;
  var templates = {};

  function embed(template_id, parameters) {
    return $.jqote(templates[template_id], parameters);
  }

  function render(template_id, element, parameters) {
    var render_template = function(e) {
      var r = embed(template_id, parameters);
      $(element).html(r);
      $(element).trigger("template_rendered");
      $(document).unbind(e);
    };

    if (loaded) {
      render_template();
    } else {
      $(document).bind("templates_ready", render_template);
    }
  }

  function load_templates() {
    $.get('/javascripts/backbone/views/templates/templates.tpl', function(doc) {
      var tpls = $(doc).filter('script');
      tpls.each(function() {
        templates[this.id] = $.jqotec(this);
      });
      loaded = true;
      $(document).trigger("templates_ready");
   });
  }

  load_templates();

  return {
    render: render,
    embed: embed
  };

}();

They look like 他们看着像是

<script id="table" data-comment="generated!!!!! to change please change table.tpl">
<![CDATA[
]]>
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM