在 Backbone.js 中使用 Jade 模板 [英] Using Jade templates in Backbone.js

查看:10
本文介绍了在 Backbone.js 中使用 Jade 模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢 Node.js 中 Jade 模板引擎的类似 HAML 的语法,并且我喜欢在 Backbone.js 中在客户端使用它.

I love the HAML-like syntax of Jade's templating engine in Node.js, and I would love to use it client-side within Backbone.js.

我已经看到 Backbone 通常使用以下样式的 Underscore.js 模板.

I've seen Backbone commonly using Underscore.js templating in the following style.

/* Tunes.js */
window.AlbumView = Backbone.View.extend({
  initialize: function() {
    this.template = _.template($('#album-template').html());
  },

  // ...
});

/* Index.html */
<script type="text/template" id="album-template">
  <span class="album-title"><%= title %></span>
  <span class="artist-name"><%= artist %></span>
  <ol class="tracks">
    <% _.each(tracks, function(track) { %>
      <li><%= track.title %></li>
    <% }); %>
  </ol>
</script>

我想看到的是一种使用 AJAX(或其他一些方法)获取 Jade 模板并在当前 HTML 中呈现它们的方法.

What I'd like to see is a way to use AJAX (or some other method) to fetch Jade templates and render them within the current HTML.

推荐答案

我能够使用 jade-browser 在客户端运行 Jade 项目.

与 Backbone 的集成很简单:我使用的是 jade.compile() 而不是 _template().

Integration with Backbone is then simple: Instead of _template() I'm using jade.compile().

HTML(脚本和模板):

<script class="jsbin" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="https://raw.github.com/weepy/jade-browser/master/jade.js"></script>
<script src="https://raw.github.com/weepy/jade-browser/master/jade-shim.js"></script>
<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<script src="http://documentcloud.github.com/backbone/backbone-min.js"></script>

<script type="template" id="test">
div.class1
  div#id
    | inner
  div#nav
    ul(style='color:red')
      li #{item}
      li #{item}
      li #{item}
      li #{item}
script
  $('body').append('i am from script in jade')
</script>

JavaScript(与 Backbone.View 集成):

var jade = require("jade");

var TestView = Backbone.View.extend({

  initialize: function() {
    this.template = jade.compile($("#test").text());
  },

  render: function() {
    var html = this.template({ item: 'hello, world'});
    $('body').append(html);
  }
});

var test = new TestView();
test.render();

这里是代码.

HERE is the code.

这篇关于在 Backbone.js 中使用 Jade 模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆