Skip to content

Commit

Permalink
Use TemplateSrv for the templating functionality
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
emanchado authored and spbnick committed Aug 28, 2020
1 parent 9edf2f3 commit b9c8630
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 15 deletions.
2 changes: 1 addition & 1 deletion plugin.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
"url": "https://redhat.com"
},
"keywords": ["singlestat", "link", "panel"],
"version": "1.0.0",
"version": "2.0.0",
"updated": "2020-03-05"
},

Expand Down
24 changes: 10 additions & 14 deletions src/singlevalue_ctrl.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand All @@ -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));
Expand All @@ -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() {
Expand Down

0 comments on commit b9c8630

Please sign in to comment.