我必须遗漏一些基本的东西,但在开发自定义jQuery小部件时,我们如何将html模板作为小部件的一部分包含在内,就像我们使用dojo自定义小部件一样?目前,我的jQuery自定义小部件正在JavaScript中生成所需的html,我正在尝试将其转换为html模板并将其包含在自定义小部件中。想法?
答案 0 :(得分:2)
您可以查看Handlebars.js。这是一个jQuery模板插件,语法非常简单
使用script
标记
<script id="entry-template" type="text/x-handlebars-template">
<div class="entry">
<h1>{{title}}</h1>
<div class="body">
{{body}}
</div>
</div>
</script>
然后像这样获取并编译该模板
var source = $("#entry-template").html();
var template = Handlebars.compile(source);
然后,您可以通过传递palceholders
这样的数据
var context = {title: "My New Post", body: "This is my first post!"}
var html = template(context);
在此之后,您将在html
变量中拥有完整的html
,您可以在$.append
等任何jQuery DOM操作方法中使用该变量。
答案 1 :(得分:1)
你真的不需要一个插件或任何想要做你想做的事情。只需使用适当的标记和您需要的任何jQuery调用创建html文件,即可轻松创建小部件。例如,您可以创建如下主页:
<html>
<head>
<!-- reference jquery library here -->
<script>
$(document).ready(function() {
$("#wdg1").load("mywidget.html");
$("#wdg2").load("mywidget.html");
});
</script>
</head>
<body>
<div id="wdg1"></div>
<div id="wdg2"></div>
</body>
</html>
然后您的mywidget.html
文件将类似于:
<script>
$(document).ready(function() {
alert("Widget loaded.");
// run whatever code you want here.
});
</script>
<span>This span was loaded as a widget.</span>