Template.residentActivityChart.rendered = function () {
  // Get resident id
  var residentId = this.data._id;

  // Get resident name
  var residentName = this.data.firstName + " " + this.data.lastInitial;

  // Get the resident activities
  var activities = Residents.findOne(residentId).activities().fetch();

  //TODO: Make sure there can be multiple activities in a single day.

  // Create a nest of activities grouped by activity date
  var nestedActivities = d3.nest()
    .key(function (activity) {
      return activity.activityDate;
    })

  // Get a sum of activities
  var summedActivities = nestedActivities.rollup(function (activity) {
      return {
        duration: d3.sum(activity, function (activity) {
          return activity.duration;
        })
      }
    })
    .entries(activities);

    summedActivities.map(function (activity) {
      // Create date and duration attributes with proper data types
      activity.date = new Date(activity.key);
      activity.duration = parseInt(activity.values.duration);

      // Delete unused key and values
      delete activity.values
      delete activity.key;
    })

  // Render the chart using MetricsGraphics charting library
  MG.data_graphic({
    title: "Daily activity in minutes.",
    description: "Showing daily activity minutes for " + residentName,
    y_label: 'Minutes',
    y_rug: true,
    data: summedActivities,
    chart_type: 'point',
    least_squares: true,
    full_width: true,
    height: 200,
    right: 40,
    target: document.getElementById('activity-chart'),
    x_accessor: 'date',
    y_accessor: 'duration',
    mouseover: function (d, i) {
      var date = d.point.date;
      var formattedDate = moment(date).format("D.M.YYYY");
      var minutes = d.point.duration;
      d3.select('#activity-chart svg .mg-active-datapoint')
        .text(formattedDate + ' ' + minutes + ' minutes');
    }
  });
}

@@ -64,50 +64,60 @@
 t re
-sident id%0A  var residentId = this.data._id
+ference to template instance%0A  const instance = this
 ;%0A%0A 
@@ -140,19 +140,21 @@
  name%0A  
-var
+const
  residen
@@ -161,20 +161,24 @@
 tName = 
-this
+instance
 .data.fi
@@ -193,20 +193,24 @@
 + %22 %22 + 
-this
+instance
 .data.la
@@ -257,173 +257,90 @@
 ties
-%0A  var activities = Residents.findOne(residentId).activities().fetch();%0A%0A  //TODO: Make sure there can be multiple activities in a single day.%0A%0A  // Create a nest of
+ from template instance%0A  const activities = instance.data.activities;%0A%0A  // Group
  act
@@ -351,16 +351,8 @@
 ies 
-grouped 
 by a
@@ -366,19 +366,21 @@
  date%0A  
-var
+const
  nestedA
@@ -507,19 +507,21 @@
 ities%0A  
-var
+const
  summedA
@@ -1577,19 +1577,21 @@
 %7B%0A      
-var
+const
  date = 
@@ -1610,19 +1610,21 @@
 ;%0A      
-var
+const
  formatt
@@ -1675,11 +1675,13 @@
     
-var
+const
  min

Use activities from template data context