Templating: A way to support object syntax for global vars (#21634)

This commit is contained in:
Torkel Ödegaard 2020-01-21 16:06:04 +01:00 committed by GitHub
parent 935d447c6a
commit 92ef8644c5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 26 additions and 0 deletions

View File

@ -31,6 +31,14 @@ describe('templateSrv', () => {
expect(target).toBe('Server1 nested');
});
it('built in vars should support objects', () => {
_templateSrv.setGlobalVariable('__dashboard', {
value: { name: 'hello' },
});
const target = _templateSrv.replace('${__dashboard.name}');
expect(target).toBe('hello');
});
it('scoped vars should support objects with propert names with dot', () => {
const target = _templateSrv.replace('${series.name} ${series.nested["field.with.dot"]}', {
series: { value: { name: 'Server1', nested: { 'field.with.dot': 'nested' } } },

View File

@ -195,6 +195,15 @@ export class TemplateSrv {
this.grafanaVariables[name] = value;
}
setGlobalVariable(name: string, variable: any) {
this.index = {
...this.index,
[name]: {
current: variable,
},
};
}
getVariableName(expression: string) {
this.regex.lastIndex = 0;
const match = this.regex.exec(expression);
@ -295,6 +304,15 @@ export class TemplateSrv {
}
}
if (fieldPath) {
const fieldValue = this.getVariableValue(variableName, fieldPath, {
[variableName]: { value: value, text: '' },
});
if (fieldValue !== null && fieldValue !== undefined) {
return this.formatValue(fieldValue, fmt, variable);
}
}
const res = this.formatValue(value, fmt, variable);
return res;
});