Skip to content

Instantly share code, notes, and snippets.

@mbostock
Last active February 9, 2016 01:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mbostock/9360565 to your computer and use it in GitHub Desktop.
Save mbostock/9360565 to your computer and use it in GitHub Desktop.
Clone Templates
license: gpl-3.0

This example demonstrates the use of cloneNode to define templates in HTML markup, modifying the instantiated template after binding to data.

<!DOCTYPE html>
<meta charset="utf-8">
<style>
#item-table {
width: 100%;
text-align: left;
}
</style>
<table id="item-table">
<thead>
<tr>
<th>Name</th>
<th>Cost</th>
<th>Count</th>
</tr>
</thead>
<tbody>
<tr class="item">
<td class="name"></td>
<td class="cost"></td>
<td class="count"></td>
</tr>
</tbody>
</table>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
var itemTemplate = d3.select(".item").remove().node();
var formatCost = d3.format("$,.2f"),
formatCount = d3.format(",d");
d3.tsv("items.tsv", type, function(error, items) {
var item = d3.select("#item-table tbody").selectAll(".item")
.data(items)
.enter().append(function() { return itemTemplate.cloneNode(true); });
item.select(".name").text(function(d) { return d.name; });
item.select(".cost").text(function(d) { return formatCost(d.cost); });
item.select(".count").text(function(d) { return formatCount(d.count); });
});
function type(d) {
d.cost = +d.cost;
d.count = +d.count;
return d;
}
</script>
name cost count
foo 1.23 10
bar 0.12 7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment