december 15, 2023
Multiplying two numbers by developing a custom Jinja function in Apache SuperSet
Knowing how to use Jinja templates in Apache Superset will extend the functionality of your dashboards, and in some cases optimize your dataset. We have written about such features in several articles: «Provisional filtering of the data in the subquery by filter values in Apache Superset«, «Creating users with limited permissions in Apache Superset» and «Displaying different dataset fields in the same table column depending on the filter value». Not many people know that it is possible to develop your own template, we will look at such an example in this article.
Don’t forget to enable Jinja templates: set ENABLE_TEMPLATE_PROCESSING to True in the \superset\docker\pythonpath_dev\superset_config.py file.
The source code of the standard Jinja templates can be found in the \superset\superset\jinja_context.py file.
To add a custom function and extend the Jinja context without doing a new docker container build, you need to define JINJA_CONTEXT_ADDONS in the \superset\docker\pythonpath_dev\superset_config.py file as follows:
JINJA_CONTEXT_ADDONS = {
‘<Template_name>’: <function body>,
}
As an example, let’s create a function tst that calculates the product of two numbers:
JINJA_CONTEXT_ADDONS = {
‘tst’: lambda x=0, y=0: x * y,
}
Stop the container and start it again:
docker-compose stop
docker-compose -f docker-compose-non-dev.yml up –d
Go to http://localhost:8088/login/, log in and log in to SQLLab to verify that our custom template works:
In the figure you can see that the function works on the input we have two numbers 2 and 3, on the output one number 6.