[Chartjs]-How do I change the interpolator used in Chart.js?

3👍

EDIT: if it’s easier i’ve now added this to my custom build of chart.js you can use either the min or the chart.js version https://github.com/leighquince/Chart.js

This can be done by changing the helpers.template function although it does have it’s limitations when trying to stick with the exact same replacing method used in the function. Example can be found here http://jsfiddle.net/leighking2/zjztm3or/ (if chart js gets update this would also need to be merged manually)

So changes that have been made (just going to give highlights of parts i have changed rather than placing the whole of chart js here)

set up a new default to express desired start and end points within tempalte string (because we are using the same method of replacing within the template function = will still be used when wanting to print a value)

Chart.defaults = {
    global: {
        templateInterpolators: {
            start: "<%",
            end: "%>"
        },
    }
};

Then within the template helper we refrence the new object and use the start and end given rather than the hard codded <% and %> as before

template = helpers.template = function (templateString, valuesObject) {
            // If templateString is function rather than string-template - call the function for valuesObject
            var interpolators = Chart.defaults.global.templateInterpolators;
            if (templateString instanceof Function) {
                return templateString(valuesObject);
            }

            var cache = {};

            function tmpl(str, data) {
                // Figure out if we're getting a template, or if we need to
                // load the template - and be sure to cache the result.
                var fn = !/\W/.test(str) ? cache[str] = cache[str] :

                // Generate a reusable function that will serve as a template
                // generator (and which will be cached).
                new Function("obj",
                    "var p=[],print=function(){p.push.apply(p,arguments);};" +

                // Introduce the data as local variables using with(){}
                "with(obj){p.push('" +

                // Convert the template into pure JavaScript
                str.replace(/[\r\t\n]/g, " ")
                    .split(interpolators.start).join("\t")
                    .replace(new RegExp("((^|" + interpolators.end + ")[^\t]*)'", "g"), "$1\r")
                    .replace(new RegExp("\t=(.*?)" + interpolators.end, "g"), "',$1,'")
                    .split("\t").join("');")
                    .split(interpolators.end).join("p.push('")
                    .split("\r").join("\\'") +
                    "');}return p.join('');");

                // Provide some basic currying to the user
                return data ? fn(data) : fn;
            }
            return tmpl(templateString, valuesObject);
        },

The limitations here are that the new interpolators can not have } in them as when given a template like tooltipTemplate = "{{if (label){}}{{= label }}: {{}}}{{= value }}"; it runs into trouble when matching the tripple }}} and my regex is not good enough to figure out how to tell it to match the last pair not the first pair, so with this method as long as you avoid ‘}’ you should be good.

Now to use it you will need to ensure you declare the interpolators you wish to use

    Chart.defaults.global.templateInterpolators = {
        start: "[[",
        end: "]]"
    };

then setup up the tempaltes, this will also need to happen for any legend templates that are specific to each graph (if you want to use them)

    Chart.defaults.global.scaleLabel = "[[= value ]]";
    Chart.defaults.global.tooltipTemplate = "[[if (label){]][[= label ]]: [[}]][[= value ]]";
    Chart.defaults.global.multiTooltipTemplate = "[[= value ]]";

and now you can just use Chart.js as normal

var ctxBar = document.getElementById("chart-bar").getContext("2d");
var ctxLine = document.getElementById("chart-line").getContext("2d");
var data = {
    labels: [1, 2, 3, 4],
    datasets: [{
        label: "My First dataset",
        fillColor: "rgba(220,220,220,0.2)",
        strokeColor: "rgba(220,220,220,1)",
        pointColor: "rgba(220,220,220,1)",
        pointStrokeColor: "#fff",
        pointHighlightFill: "#fff",
        pointHighlightStroke: "rgba(220,220,220,1)",
        data: [65, 34, 21, 11]
    }, ]
};




var myBarChart = new Chart(ctxBar).Bar(data);
var myLineChart = new Chart(ctxLine).Line(data);

Leave a comment