How do I change the interpolator used in Chart.js?

I've been looking for some alternatives regarding chart libraries and the one that suits my needs, Chart.js . However, I cannot use it because the interpolators used in Chart.js are used in EJS templates from Express like <%

and %>

.

I've used some other libraries like underscore.js where you can modify the interpolators to prevent any conflict with the Javascript libraries.

Any help would be appreciated ...

+3


source to share


1 answer


EDIT: if it's easier, I added this to my own chart.js build, you can use either min or the chart.js version https://github.com/leighquince/Chart.js

This can be done by modifying the helpers.template function, although it has limitations when trying to stick to the same replacement method used in this function. An example can be found here http://jsfiddle.net/leighking2/zjztm3or/ (if the js diagram gets an update, this also needs to be merged manually)

So the changes that have been made (just going to give the main points that I changed instead of posting the whole js graph here)

set up a new default to express the desired start and end points in the tempalte string (because we use the same replacement method inside the template function = will still be used when you want to print the value)

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

      

Then in the template helper we return a new object and only use the start and end value, not the hard-coded <% 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 limitation here is that new interpolators cannot have} in them, because given a pattern, for example, tooltipTemplate = "{{if (label){}}{{= label }}: {{}}}{{= value }}";

it encounters difficulties in matching a triplex}}}, and my regex is not good enough to figure out how to say it should 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 need to make sure you declare the interpolators you want to use

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

      

then tune tempaltes, this should also happen for any legend patterns specific to each plot (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 usual

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);

      

+3


source







All Articles