diff --git a/docs/sources/reference/templating.md b/docs/sources/reference/templating.md index 71ce6bdd2ae..3ef32b1b10f 100644 --- a/docs/sources/reference/templating.md +++ b/docs/sources/reference/templating.md @@ -52,6 +52,7 @@ Filter Option | Example | Raw | Interpolated | Description `csv`| ${servers:csv} | `'test1', 'test2'` | `test1,test2` | Formats multi-value variable as a comma-separated string `distributed`| ${servers:distributed} | `'test1', 'test2'` | `test1,servers=test2` | Formats multi-value variable in custom format for OpenTSDB. `lucene`| ${servers:lucene} | `'test', 'test2'` | `("test" OR "test2")` | Formats multi-value variable as a lucene expression. +`percentencode` | ${servers:percentencode} | `'foo()bar BAZ', 'test2'` | `{foo%28%29bar%20BAZ%2Ctest2}` | Formats multi-value variable into a glob, percent-encoded. Test the formatting options on the [Grafana Play site](http://play.grafana.org/d/cJtIfcWiz/template-variable-formatting-options?orgId=1). diff --git a/public/app/features/templating/specs/template_srv.test.ts b/public/app/features/templating/specs/template_srv.test.ts index 7805341d1a2..4288b5f3928 100644 --- a/public/app/features/templating/specs/template_srv.test.ts +++ b/public/app/features/templating/specs/template_srv.test.ts @@ -275,6 +275,11 @@ describe('templateSrv', () => { expect(result).toBe('test,test2'); }); + it('multi value and percentencode format should render percent-encoded string', () => { + const result = _templateSrv.formatValue(['foo()bar BAZ', 'test2'], 'percentencode'); + expect(result).toBe('%7Bfoo%28%29bar%20BAZ%2Ctest2%7D'); + }); + it('slash should be properly escaped in regex format', () => { const result = _templateSrv.formatValue('Gi3/14', 'regex'); expect(result).toBe('Gi3\\/14'); diff --git a/public/app/features/templating/template_srv.ts b/public/app/features/templating/template_srv.ts index 74da017bb93..07656924c9c 100644 --- a/public/app/features/templating/template_srv.ts +++ b/public/app/features/templating/template_srv.ts @@ -77,6 +77,15 @@ export class TemplateSrv { return '(' + quotedValues.join(' OR ') + ')'; } + // encode string according to RFC 3986; in contrast to encodeURIComponent() + // also the sub-delims "!", "'", "(", ")" and "*" are encoded; + // unicode handling uses UTF-8 as in ECMA-262. + encodeURIComponentStrict(str) { + return encodeURIComponent(str).replace(/[!'()*]/g, (c) => { + return '%' + c.charCodeAt(0).toString(16).toUpperCase(); + }); + } + formatValue(value, format, variable) { // for some scopedVars there is no variable variable = variable || {}; @@ -118,6 +127,13 @@ export class TemplateSrv { } return value; } + case 'percentencode': { + // like glob, but url escaped + if (_.isArray(value)) { + return this.encodeURIComponentStrict('{' + value.join(',') + '}'); + } + return this.encodeURIComponentStrict(value); + } default: { if (_.isArray(value)) { return '{' + value.join(',') + '}';