javascript - 在 Backbone.js 中使用 Jade 模板

标签 javascript backbone.js pug underscore.js

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

我见过 Backbone 通常使用以下样式的 Underscore.js 模板。

/* 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 中呈现它们的方法。

最佳答案

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

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

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 是代码。

关于javascript - 在 Backbone.js 中使用 Jade 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8528885/

相关文章:

javascript - 主干提取 - "url"必须指定属性或函数错误

pug - Sails 中 csrf token 的 Jade 等价物

html - 使用 Jade、NodeJS、Express 的动态 html 页面

JavaScript:在 `for loop` 语句中工作的 `if` 在 `ternary` 语句中不起作用?为什么?

javascript - 限制html5视频的最小尺寸

javascript - 从 HTML 编码的 UNIX 路径中剥离文件名

javascript - InnerView 不响应其模板中的 DOM 事件

javascript - 如何在 vue-google-maps 中设置 infoWindow - Vue.js

javascript - 如何使用backbone.js从javascript闭包内部调用其他内部方法?

node.js - 包含父目录中的 Jade block