Skip to content

Instantly share code, notes, and snippets.

@ErikOnBike
Last active September 30, 2018 13:32
Show Gist options
  • Save ErikOnBike/4ef1c2af7d64023532745f0d61f08c18 to your computer and use it in GitHub Desktop.
Save ErikOnBike/4ef1c2af7d64023532745f0d61f08c18 to your computer and use it in GitHub Desktop.
Basic usage repeat group in d3-template
license: gpl-3.0
scrolling: yes

This example demonstrates the basic usage of a repeat group in d3-template.

Since loading the data can take a little time, the template might be visible. To prevent this, the ul element could be made invisible through CSS until data is provided.

<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
font-family: "Helvetica Neue", Helvetica, sans-serif;
}
</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>
<p>
D3-modules by Mike Bostock sorted by commit date (most recent first)
<ul data-repeat='{{d.sort(sortModules)}}'>
<li>
<a href="{{d.html_url}}">{{d.name}}</a>,
last commit <span>{{d3.timeFormat("%-d %B %Y")(d.pushed_at)}}</span>
</li>
</ul>
</p>
<script>
function sortModules(a, b) {
if(a.pushed_at > b.pushed_at) {
return -1;
} else if(a.pushed_at === b.pushed_at) {
return a.name.localeCompare(b.name);
} else {
return +1;
}
}
// See https://developer.github.com/v3/repos/#list-user-repositories
d3.json("https://api.github.com/users/d3/repos?per_page=100", function(error, data) {
if(error) {
throw error;
}
// Change commit field from string to date
data.forEach(function(repo) {
repo.pushed_at = new Date(repo.pushed_at);
repo.pushed_at.setHours(12, 0, 0, 0); // All same time to allow 'understandable' sorting
});
// Create template and render data
d3.select("ul")
.template()
.render(data)
;
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment