Skip to main content

JavaScript Code

Dynamic Text Panel supports the integration of JavaScript code snippets that can add Handlebars helpers and event handlers.

Version

Dynamic Text Panel supports JavaScript since version 2.2.0.

JavaScript code in Dynamic Text Panel.

Parameters

Version

The Dynamic Text Panel supports context starting from version 4.3.0.

Starting from the release 4.3.0, we allowed access to the panel data panelData and selected data frame data via a new object context.

In addition, we are actively working on refactoring existing JavaScript and Grafana parameters to include in the context.

Start typing the context word in the Before Content Rendering or After Content Ready boxes and see the latest list of all available features.

Simplified access to the panel data and selected data frame and some other features.
Simplified access to the panel data and selected data frame and some other features.
ParameterDescription
context.dataData from data sources. The display of one or multiple data rows from the selected data frame or from all data frames is determined by the Render template option. It can be one of three values: Every Row, All Rows, and All data
context.dataFrameSelected Data Frame for Every Row, All Rows templates
context.grafana.eventBusPublish and subscribe to application events. Supported since Dynamic Text Panel 4.0.0.
context.grafana.getLocale()Returns the user's locale: 'en', 'fr', 'es', and so on.
context.grafana.locationServiceThe locationService works with the browser location and history. Supported since Dynamic Text Panel 3.1.0.
context.grafana.replaceVariables()The replaceVariables() function to interpolate variables. Supported since Dynamic Text Panel 3.1.0.
context.grafana.timeRangeTime range of the current dashboard. Supported since Dynamic Text Panel 3.1.0.
context.grafana.timeZoneTime zone of the current dashboard. Supported since Dynamic Text Panel 3.1.0.
context.handlebarsHandlebars library.
context.panelDataPanel data

Custom Handlebars helper

You can add a custom Handlebars helper to replace the field's value according to some pattern.

{{replace Test "Pattern" "Replaced"}}

JavaScript Code

Here we register a function with the replace helper that takes three arguments:

  1. context is an object that contains the data for the template.
  2. pattern is the text to be searched for.
  3. replacement is the text to be used to replace the pattern.

Then we call this function and pass the pattern and replacement arguments to it.

handlebars.registerHelper("replace", (context, pattern, replacement) =>
context.replace(pattern, replacement)
);
A custom helper to replace data in the returned data.
A custom helper to replace data in the returned data.

Event Handler

To respond to a button click, you can add a custom event handler.

<button onclick="myFunc()">{{test}}</button>

JavaScript Code

This code snippet defines a function called myFunc. The function takes no arguments and returns no value. The body of the function calls the alert() function to display the text "Bonjour!" in a dialog box.

myFunc = () => {
alert("Bonjour!");
};

Internationalization

Grafana 9 and up offers internationalization, which most of the plugins do not yet have full access to.

Meanwhile, you can use the getLocale() method to get a value for the chosen locale and display terms from a defined dictionary.

Content

This code snippet uses the translate helper to translate the text "Hello" to the current language. Text translation will be performed if the translate helper is defined, otherwise the text "Hello" will be displayed.

{{translate "Hello"}}

Default content

This code snippet uses the translate helper to show the translation of a default message if the query does not return any results.

{{translate "Default"}}

JavaScript Code

docs/volkovlabs-dynamictext-panel/js/translate.js
loading...

Time Zone and Range

You can display the selected dashboard, browser's time zone, and time ranges in Grafana.

Dynamic Text Panel allows displaying an updated time zone and time ranges in Grafana.
Dynamic Text Panel allows displaying an updated time zone and time ranges in Grafana.

Content

Use the following for the Content

<h2>Dashboard {{tz}}</h1>
<h2>Browser {{browser}}</h1>

```json
{{{json (range)}}}
```

JavaScript Code

Use the following for the JavaScript->Before Content Rendering

handlebars.registerHelper('tz', () => timeZone);
handlebars.registerHelper('range', () => timeRange);
handlebars.registerHelper('browser', () => Intl.DateTimeFormat().resolvedOptions().timeZone);

Automatic scrolling

If the table does not fit into the allocated panel area, you can add automatic scrolling using JavaScript with an adjustable interval.

Automatic scrolling of a table using Dynamic Text Panel.
Automatic scrolling of a table using Dynamic Text Panel.

Content

Use the following for the Content:

<table id="dataTable" width="100%">
<tr>
<th>Title</th>
<th>Date</th>
<th>Category</th>
</tr>
{{#each data}}
<tr>
<td>{{title}}</td>
<td>{{date pubDate 'MMM, DD YYYY'}}</td>
<td>{{category}}</td>
</tr>
{{/each}}
</table>

JavaScript Code

Use the following for the JavaScript->Before Content Rendering:

JavaScript for autoscrolling
docs/volkovlabs-dynamictext-panel/js/scroll.js
loading...

Unique values

You can sort out unique values from the data object using the unique helper that was implemented by the community member goncalobsantos.

Content

Use the following for the Content:

<div>{{#each (unique data "hostname.keyword")}}{{this}}; {{/each}}</div>

JavaScript Code

Use the following for the JavaScript->Before Content Rendering:

handlebars.registerHelper("unique", (context, key) => {
return [...new Set(context.map((item) => item[key]))];
});

Dashboard Variables

You can use the replaceVariables function to replace dashboard variables in the JavaScript code.

const bonjour = replaceVariables("${variable}");
console.log(bonjour.toUpperCase())

REST API

Dynamic Text Plugin submits REST API request.

Dynamic Text Plugin submits REST API request.
Dynamic Text Plugin submits REST API request.

Content

Into the Content:

<form id="myForm">
<input name="firstName" />
<input name="lastName" />

<button>submit</button>
</form>

JavaScript Code

Into the JavaScript->After Content Ready

JavaScript to submit REST request
/**
* Form Element
*/
const form = document.querySelector("#myForm");

/**
* Handle Submit
*/
const handleSubmit = (event) => {
/**
* Prevent Default submition
*/
event.preventDefault();

const formData = new FormData(event.target);
const data = Object.fromEntries(formData);

console.log(data);
/**
* Result: { firstName: '', lastName: '' }
*/

/**
* Your request to send form
*/
fetch("url", {
method: "POST",
body: JSON.stringify(data),
});
};

form.addEventListener("submit", handleSubmit);

return () => {
form.removeEventListener("submit", handleSubmit);
};

JSON parsing

The community member havedill asked how to parse a JSON data format in the case when the transformation Convert field type is not available.

We believe the solution might be helpful for many, so here is how you can do it.

.
.

JSON example

{ "title": { "text": "Area Chart", "size": 45, "font": "Arial" } }
{ "title": { "text": "Bar Chart", "color": "black" } }

Content

{{{json (parse JSON)}}}

JavaScript

handlebars.registerHelper("parse", (context) => JSON.parse(context));

Anonymizer

Anonymizer is the tool we created for internal purposes of converting real production data into dummy values in order to have our dashboards demo-ready. Anonymizer is another great example of how embedded JavaScript can simplify tedious and repetitive tasks.

You can find all you need in the following blog post:

Streamline demos with Dynamic Text Anonymizer.
Streamline demos with Dynamic Text Anonymizer.

If you are a visual style learner, you can watch the video. It covers the same ground.

Convert dashboard values on the fly for demo purposes.