理解Jquery模板

The*_*ner 7 jquery jquery-plugins jquery-templates

我正在阅读并尝试理解Jquery模板示例.

<script id="movieTemplate" type="text/x-jquery-tmpl"> 
  {{tmpl "titleTemplate"}}
  <tr class="detail"><td>Director: ${Director}</td></tr>

</script>

<table><tbody id="movieList"></tbody></table>

<script>
var movies = [
  { Name: "The Red Violin", Director: "François Girard" ,Producer : "ssss" },
  { Name: "Eyes Wide Shut", Director: "Stanley Kubrick" },
  { Name: "The Inheritance", Director: "Mauro Bolognini" }
];

/* Convert the markup string into a named template,
   referenced by the {{tmpl}} tag */
$.template( "titleTemplate", "<tr class='title'><td>${Name}</td></tr>" );

/* Render the movies data, using the named template as a nested template */
$( "#movieTemplate" ).tmpl( movies ).appendTo( "#movieList" );
</script>
Run Code Online (Sandbox Code Playgroud)

在这个示例程序中,我无法理解:

/*将标记字符串转换为命名模板,由{{tmpl}}标记*/引用

当我们调用:$("#movieTemplate").tmpl(电影)它正在调用模板,我们正在使用输入电影调用模板函数并将其附加到movieslistid

如果我删除代码

$.template( "titleTemplate", "<tr class='title'><td>${Name}</td></tr>" );
Run Code Online (Sandbox Code Playgroud)

这是行不通的.你能解释为什么我们需要这个以及它在这里做了什么:/*将标记字符串转换为命名模板,意思是全部..

我试着阅读并且发现我没有得到澄清

Tom*_*lak 9

这包含对名为"titleTemplate"的模板的引用,该模板尚未定义:

<script id="movieTemplate" type="text/x-jquery-tmpl"> 
  {{tmpl "titleTemplate"}}
  <tr class="detail"><td>Director: ${Director}</td></tr>
</script>
Run Code Online (Sandbox Code Playgroud)

这一行定义了缺少的模板:

$.template( "titleTemplate", "<tr class='title'><td>${Name}</td></tr>" );
Run Code Online (Sandbox Code Playgroud)

这是另一种说法

<script id="titleTemplate" type="text/x-jquery-tmpl"> 
  <tr class='title'><td>${Name}</td></tr>
</script>
Run Code Online (Sandbox Code Playgroud)

本质上,该示例显示您可以通过两种方式定义模板

  • 声明性地在HTML源代码中作为<script type="text/x-jquery-tmpl">元素
  • 以编程方式从字符串到 $.template()