预填充jsrender模板

Prefill jsrender template

本文关键字:模板 jsrender 填充      更新时间:2023-09-26

如何将select(具有选项)呈现为表的一部分?

$('select').append($('<option>').text('single'));
$('table').append($('#rowTmpl').render({name:'peter'}));
th,td {border:1px solid black;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rawgit.com/BorisMoore/jsrender/master/jsrender.min.js"></script>
<div style="display:none" id="statis">
  <select></select>
</div>
<script id="rowTmpl" type="text/x-jsrender">
  <tr>
    <td>{{:name}}</td>
    <td>{{include tmpl=#statis /}}</td>
  </tr>
</script>
<table>
  <tr>
    <th>Name</th>
    <th>Stat</th>
  </tr>
</table>

第一行javascript将一个选项附加到select(第四行html)。第二个javascript行应该为人员peter向表中呈现一行。

问题:

  1. 我无法将div设置为脚本标记,因为第一行javascript将找不到select标记
  2. 我无法通过{{include渲染div,因为#statis是一个div,而不是脚本标记

您的{{include}有语法错误。应该是:

<td>{{include tmpl="#statis" /}}</td>

事实上,您可以在隐藏的div中声明JsBinder模板,但这通常不是一个好的做法,因为可能会有副作用。请参阅:https://stackoverflow.com/a/25609895/1054484.

您还可以从字符串中声明模板,并根据需要预先动态操作字符串。

另请参阅:

  • http://www.jsviews.com/#compiletmpl
  • http://www.jsviews.com/#tagsyntax@组成

$('select').append($('<option>').text('single'));
$('table').append($('#rowTmpl').render({name:'peter'}));
th,td {border:1px solid black;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rawgit.com/BorisMoore/jsrender/master/jsrender.min.js"></script>
<div style="display:none" id="statis">
  <select></select>
</div>
<script id="rowTmpl" type="text/x-jsrender">
  <tr>
    <td>{{:name}}</td>
    <td>{{include tmpl="#statis" /}}</td>
  </tr>
</script>
<table>
  <tr>
    <th>Name</th>
    <th>Stat</th>
  </tr>
</table>