jQuery custom widgets: how can I include a html template?
-
10-06-2021 - |
Question
I must be missing something basic here but while developing a custom jQuery widget, how do we include a html template as part of the widget like we do with dojo custom widgets? Currently, my jQuery custom widget is generating the needed html in JavaScript and I am trying to take that out into a html template and include it with the custom widget. Thoughts?
Solution
You can have a look at Handlebars.js. THis is a jQuery template plugin and The syntax is pretty easy
Declare a Templae with script
tag
<script id="entry-template" type="text/x-handlebars-template">
<div class="entry">
<h1>{{title}}</h1>
<div class="body">
{{body}}
</div>
</div>
</script>
Then fetch and compile that template like this
var source = $("#entry-template").html();
var template = Handlebars.compile(source);
Then you can render that template by passing data for palceholders
like this
var context = {title: "My New Post", body: "This is my first post!"}
var html = template(context);
After this you will have the ful html
in html
variable which you can use in any jQuery DOM manipulation method like $.append
.
OTHER TIPS
You don't really need a plugin or anything fancy to do what you're trying to do. Widgets can be created easily enough by simply creating html files with the appropriate markup and any jQuery calls you need. For example you can create a main page like this:
<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>
And then your mywidget.html
file will look something like:
<script>
$(document).ready(function() {
alert("Widget loaded.");
// run whatever code you want here.
});
</script>
<span>This span was loaded as a widget.</span>