From b9c8630f51b85ca0b4b8242fd07298d1714bd115 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20Manchado=20Vel=C3=A1zquez?= Date: Fri, 28 Aug 2020 10:30:44 +0200 Subject: [PATCH] Use TemplateSrv for the templating functionality It turns out that TemplateSrv was passed to the plugin, so it can be used. So, use that instead of doing the substituting by hand. One side-effect of that change, which is the reason for it in the first place, is that now "global variables" are also substituted. --- plugin.json | 2 +- src/singlevalue_ctrl.js | 24 ++++++++++-------------- 2 files changed, 11 insertions(+), 15 deletions(-) diff --git a/plugin.json b/plugin.json index 6fa6cba..5c8dd80 100644 --- a/plugin.json +++ b/plugin.json @@ -10,7 +10,7 @@ "url": "https://redhat.com" }, "keywords": ["singlestat", "link", "panel"], - "version": "1.0.0", + "version": "2.0.0", "updated": "2020-03-05" }, diff --git a/src/singlevalue_ctrl.js b/src/singlevalue_ctrl.js index 05e96fb..7a09d50 100644 --- a/src/singlevalue_ctrl.js +++ b/src/singlevalue_ctrl.js @@ -2,7 +2,7 @@ import { MetricsPanelCtrl } from 'app/plugins/sdk'; import { PanelEvents } from '@grafana/data'; class SingleValueCtrl extends MetricsPanelCtrl { - constructor($scope, $injector) { + constructor($scope, $injector, templateSrv) { super($scope, $injector); const panelDefaults = { @@ -17,6 +17,7 @@ class SingleValueCtrl extends MetricsPanelCtrl { } } + this.templateSrv = templateSrv; this.events.on(PanelEvents.panelInitialized, this.adjustFontSize.bind(this)); this.events.on(PanelEvents.editModeInitialized, this.onInitEditMode.bind(this)); this.events.on(PanelEvents.dataReceived, this.onDataReceived.bind(this)); @@ -40,19 +41,14 @@ class SingleValueCtrl extends MetricsPanelCtrl { return; } - // Imitate the "templating" syntax of the table panel plugin - this.text = this.panel.textTemplate.replace( - /\${__cell_(\d+)}/g, - (match, cellNumber) => ( - data[cellNumber] - ) - ); - this.url = this.panel.urlTemplate.replace( - /\${__cell_(\d+)}/g, - (match, cellNumber) => ( - data[cellNumber] - ) - ); + // Substitute variables in the two templates + const vars = {}; + for (let key in data) { + let value = data[key]; + vars["__cell_" + key] = { value: value, text: value ? value.toString() : '' }; + } + this.text = this.templateSrv.replace(this.panel.textTemplate, vars); + this.url = this.templateSrv.replace(this.panel.urlTemplate, vars, encodeURIComponent); } render() {