Query template variable for custom datasource

Couldn’t find any questions/resources on this, hope I didn’t miss it.

What I want to do: Insert a variable into a query using my custom datasource

Details:
I’ve created a custom datasource plugin. It is based on the typescript datasource template. The idea is similar to the simplejson plugin: create a json request based on a user’s query. I’d like to set a template variable to control a field in the query, similar to $app or $server from this example:

If I have created a variable called $device, with the Graphite datasource, I am able to simply type into the query field “$app” and it will be set by the corresponding variable. For my custom datasource, this doesn’t work. However, typing “$device” in the title for the graph does set the title to the value of the variable! I am guessing I need to hook something up in either datasource or query_ctrl but I have no clue what.

What I’ve tried:
Simply typing “$device” into the query field:


This makes the query literally “$device” instead of the value of the $app variable.

In the datasource code, I can also check for the if the variable exists and put its value into the query, but this doesn’t reflect the change in the UI and is very hacky. I tried reading through Graphite source to figure out how they do it but couldn’t figure it out.

I am guessing it has something to do with templateSrv(), but I have no clue how.

Appreciate any and all help.

In case anyone else having the same issue ends up here:

If you type $<variableName> into the field, then navigate away (for example, by clicking on the “General” tab) then come back to the Metrics tab, the variable should turn blue. Make sure the name you entered matches the variable name.

In your query function, the field replaced with the variable will now be $<variableName>. You can obtain the variable’s value with the function this.templateSrv.replace("$<variableName>").

The source for templateSrv has been helpful for me: https://github.com/grafana/grafana/blob/master/public/app/features/templating/template_srv.ts