Skip to content

Instantly share code, notes, and snippets.

@ErikOnBike
Last active September 30, 2018 13:37
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 ErikOnBike/f36ce2b4c88ef525d0cfe34a766d8067 to your computer and use it in GitHub Desktop.
Save ErikOnBike/f36ce2b4c88ef525d0cfe34a766d8067 to your computer and use it in GitHub Desktop.
Basic usage d3-template
license: gpl-3.0
height: 300
scrolling: yes

This example demonstrates the basic usage of d3-template. The example is shown on the main README of the repo.

<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
font-family: "Helvetica Neue", Helvetica, sans-serif;
}
li {
cursor: pointer;
}
</style>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://unpkg.com/d3-template-plugin/build/d3-template.min.js"></script>
<div class="person">
<div>
<span>{{`Name: ${d.name}`}}</span>
</div>
<div>
<span>{{`Birthdate: ${d3.timeFormat("%-d %B %Y")(d.birthdate)}`}}</span>
</div>
<div>
<span>Honours given name to:</span>
<ol data-repeat="{{d.honours.given}}">
<li>{{d}}</li>
</ol>
</div>
</div>
<script>
// Add event handler to list element before template creation
d3.select(".person ol li")
.on("click", function(d, i) {
window.alert("Honour " + (i + 1) + " given is: " + d);
})
;
// Turn selection into a template
// This will remove some elements from the DOM as well as add some attributes to elements
// for identification.
d3.select(".person")
.template()
;
// ...
// Render data onto earlier created template
// Information retrieved from https://en.wikipedia.org/wiki/Alan_Turing#Awards,_honours,_recognition,_and_tributes
d3.select(".person")
.render({
name: "Alan Turing",
birthdate: new Date(1912, 5, 23),
honours: {
received: [
"Order of the British Empire",
"Fellow of the Royal Society"
],
given: [
"Good–Turing frequency estimation",
"Turing completeness",
"Turing degree",
"Turing fixed-point combinator",
"Turing Institute",
"Turing Lecture",
"Turing machine examples",
"Turing patterns",
"Turing reduction",
"Turing switch"
]
}
})
;
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment