在KnockoutJS中使用外部模板

Keb*_*dnK 15 templates external knockout.js knockout-templating

可以像这样在KnockoutJS中使用外部模板吗?

<script type="text/html" id="a_template" src="templates/a_template.html">
</script>
Run Code Online (Sandbox Code Playgroud)

我尝试过这个解决方案,但没有让它运转起来.

son*_*iic 23

您可以使用jquery将html动态加载到脚本元素中,然后基于此执行knockout.

<script type="text/html" id="template_holder"></script>
<script type="text/javascript">
$('#template_holder').load('templates/a_template.html', function() {
  alert('Load was performed.');
  //knockout binding goes here
});</script>
Run Code Online (Sandbox Code Playgroud)

你的敲除绑定必须在回调函数中完成,否则你有可能在页面加载之前尝试绑定

更新这是我在jsfiddle上编写的一个示例,用于演示动态加载:http://jsfiddle.net/soniiic/2HxPp/


Joh*_*les 6

你也可以看看:

https://github.com/ifandelse/Knockout.js-External-Template-Engine

  • *在您的HTML文件中,引用jQuery,jquery-tmpl(如果您使用的是jquery模板),knockout.js,TrafficCop,infuser和koExternalTemplateEngine.js文件* - 它看起来不是很轻量级:) (2认同)