Closed zpbx closed 10 years ago
1-1. write template in a dummy script element with a id (prefixed with template-
)
<script type="text/template" id="template-my-classmates">
<ul>
<% _.each(data, function(person) { %>
<li><%= person.name + ': ' + person.age %></li>
<% }) %>
</ul>
</script>
1-2. prepare data
var myClassmates = [
{name: 'Peter', age: '31'},
{name: 'Judy', age: '26'}
]
1-3. render template to get html code
var html = _.template.render('my-classmates', myClassmates)
2-1. don't touch html page, but add a template in js
_.template.add('id', [
'<ul>',
'<% _.each(data, function(person) { %>',
'<li><%= person.name + \': \' + person.age %></li>',
'<% }) %>',
'</ul>'
].join(''))
2-2. prepare data (same as 1-2)
2-3. render template to get html code (same as 1-3)
在 Jedi 中写前端模板:
script @id='template-my-classmates' @type='text/template'
!
<ul>
<% _.each(data, function(person) { %>
<li><%= person.name + ': ' + person.age %></li>
<% }) %>
</ul>
由于在目前的 Jedi 实现中,必须要给脚本源加一层 HTML 注释才能保证原样输出,因此我们在获取模板时需要过滤掉这一层注释。(参 _.templateSettings.needStripCommentTag
配置和 _.template.__stripCommentTag()
方法。)
概述
这个模块是对 Underscore 提供的前端模板引擎的一个封装。