jquery 模板 - 导入文件?

发布于 2024-10-31 20:31:01 字数 621 浏览 0 评论 0原文

我正在使用backbone.js,但据我所知,它并不关心你使用什么模板系统。目前我正在尝试 Mustache.js,但我对其他的持开放态度。不过,我对必须将模板放入字符串中的方式有​​点恼火:

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

我希望我是否可以从不同的文件或其他文件中加载它。我希望能够拥有模板文件以简化事情。例如,如果我把它全部放在一个字符串中,我就不能有中断(当然我可以有 html 中断,但这不是重点)。当队伍开始变得很长之后,就变得难以管理。

尖端?

I'm working with backbone.js, but as far as I've seen, it doesn't care what templating system you use. Currently I'm trying out mustache.js, but I'm open to other ones. 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). After the line starts to get very long, it becomes unmanageable.

Tips?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

无声静候 2024-11-07 20:31:01

更新(4/11/14):

正如下面OP的回答:

不幸的是,jQuery 团队已将模板功能从 jQuery Core 中移出。该代码仍然可以作为库在这里使用: github.com/BorisMoore/jquery-tmpl 和这里: github.com/borismoore/jsrender

原始答案:

我刚刚用过这个几个小时前:
http://api.jquery.com/category/plugins/templates/

这是一个官方 jQuery 插件(即开发人员认可它)。

这是从字符串以外的其他内容加载模板所需的函数: http://api.jquery.com /template/

下面是在 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" );
}

它位于

另请注意,“从不同文件加载”本质上与“读取文件”然后“从字符串加载”相同。

Updated (4/11/14):

As answered by OP below:

Unfortunately, the jQuery team has moved the templating functionality out of jQuery Core. The code is still available as a library here: github.com/BorisMoore/jquery-tmpl and here: github.com/borismoore/jsrender

Original Answer:

I just used this a couple of hours ago:
http://api.jquery.com/category/plugins/templates/

It's an official jQuery plugin(i.e. the devs endorse it).

This is the function you need to use for loading templates from things other than strings: http://api.jquery.com/template/

Here's the code to have a template in 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.
Note the type="text/x-jquery-tmpl". If you omit that, it will try to parse it as JavaScript(and fail horribly).

Also note that "loading from a different file" is essentially the same as "reading a file" and then "loading from a string".

心安伴我暖 2024-11-07 20:31:01

编辑

我刚刚找到了这个 jQuery 插件 - http://markdalgleish.com/projects/tmpload / 完全符合您的要求,并且可以与 $.tmpl 结合使用


我构建了一个轻量级模板管理器,它通过 Ajax 加载模板,它允许您将模板分成更易于管理的模块。它还执行简单的内存缓存以防止不必要的 HTTP 请求。 (为了简洁起见,我在这里使用了 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
  }

};

然后您可以按如下方式使用此代码,通过回调处理模板数据:

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

Edit

I just found this jQuery plugin - http://markdalgleish.com/projects/tmpload/ Does exactly what you want, and can be coupled with $.tmpl


I have built a lightweight template manager that loads templates via Ajax, which allows you to separate the templates into more manageable modules. It also performs simple, in-memory caching to prevent unnecessary HTTP requests. (I have used jQuery.ajax here for brevity)

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' });
});
秋日私语 2024-11-07 20:31:01

我们使用jqote2与backbone,因为它比jQuery更快,正如你所说,有很多:)

我们将所有模板放在一个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
  };

}();

它们看起来像

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

We are using jqote2 with backbone because it's faster than jQuery's, as you say there are many :)

We have all our templates in a single tpl file, we bind to our template_rendered so we can add jquery events etc etc

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>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文