Skip to content

Instantly share code, notes, and snippets.

@kgjenkins
Last active December 10, 2015 21:52
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 kgjenkins/ffe8a8981ef6b7c86012 to your computer and use it in GitHub Desktop.
Save kgjenkins/ffe8a8981ef6b7c86012 to your computer and use it in GitHub Desktop.
Customize CartoDB infowindows using Mustache and SQL

Customize CartoDB infowindows using Mustache and SQL

Infowindows are those little windows that can be configured to pop up when we click or hover over a feature (point, line, or polygon) in CartoDB. One of the great things about CartoDB is that it provides a simple interface that lets us control which attributes appear in the infowindow and which ones are hidden. (Because no one looking at your map really wants to see the value of FID, OBJECTID, ID2, AREA, AND PERIMETER, especially when FID, OBJECTID, and ID2 are all the same, and AREA and PERIMETER are incorrect because they weren't recalculated after clipping...)

cartodb-infowindow-ui

But CartoDB also gives us full access to the HTML behind the infowindow. (They added this feature back in 2013.) So if we know even just a little bit about HTML, we can customize the infowindow even further:

cartodb-infowindow-html

Notice that the line "mood:" appears even though there is no value assigned for the B triangle. Wouldn't it be nice to skip this line altogether whenever there is no corresponding value in the data table?

To render the infowindow templates into HTML, CartoDB uses Mustache "logic-less templates" to replace {{mood}} in the template with the actual value of the mood column from the data table. Despite Mustache's claim of "logic-less", it actually does support some simple logic.

In Mustache, a "section" begins with a tag like {{#mood}} and ends with {{/mood}}, and whatever is in between those tags will only display if the value of the mood column is true. In other words, the section content will NOT display if the value of mood is null, false, zero, or blank. (We could also do the opposite by starting the section with {{^mood}}.) So we could improve our mood by doing something like this:

cartodb-infowindow-html-mustache-1

But what if we want to use more complex logic, like displaying a special note when the value of score is greater than 80? Mustache doesn't handle those sorts of comparisons, but we can instead use SQL to add an extra column highscore that will evaluate to true or false:

cartodb-infowindow-sql

And then we can create a section that will only display when highscore is true:

cartodb-infowindow-html-mustache-2

This basic technique could be used to add all sorts of customizations to the CartoDB infowindows. Have fun!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment