Skip to main content

Show HTML

Plotly

For interactive visualizations using Plotly, it is recommended to use the dedicated PlotlyView.

This guide explains how to add a WebView to an editor. This could for instance be used to incorporate interactive visualizations or present other dynamic or static HTML (web) content:

Implementation

Example of how an interactive visualization in a web view could look like (source: plot.ly)

There are 3 ways to pass the HTML content to a WebResult:

  1. From a URL
  2. From a static HTML file
  3. From a dynamic HTML content

From a URL

You can point to a live URL and use that HTML page:

from viktor import ViktorControllerfrom viktor.views import WebResultfrom viktor.views import WebViewclass Controller(ViktorController):    ...    @WebView('Python wiki', duration_guess=1)    def get_web_view(self, params, **kwargs):        return WebResult(url='https://en.wikipedia.org/wiki/Python_(programming_language)')

From a static HTML file

If the HTML page is always the same (it is not necessary to generate it on every call), use the from_path method to construct a WebResult:

from pathlib import Pathfrom viktor import ViktorControllerfrom viktor.views import WebResultfrom viktor.views import WebViewclass Controller(ViktorController):    ...    @WebView('Hello page', duration_guess=1)    def get_web_view(self, params, **kwargs):        static_html_path = Path(__file__).parent / 'page.html'        return WebResult.from_path(static_html_path)

page.html (in this example next to controller.py):

<html>
Hello Everyone!
</html>

From dynamic HTML content

If the HTML page is dependent on some input (so needs to be generated on every call), use the html argument in WebResult:

from io import StringIOfrom viktor import ViktorControllerfrom viktor.views import WebResultfrom viktor.views import WebViewclass Controller(ViktorController):    ...    @WebView('Hello page', duration_guess=1)    def get_web_view(self, params, **kwargs):        name = 'John Doe'        html_text = f'<html>Hello {name}</html>'        return WebResult(html=html_text)

A web view can be combined with a data view using a WebAndDataView

Interactive visualizations

A very useful application of the web view is for interactive visualizations (for instance maps/graphs). The following Python libraries offer the functionality to export interactive visualizations as an HTML page:

Testing

New in v13.3.0

mock_View decorator for easier testing of view methods

Methods decorated with @WebView or @WebAndDataView need to be mocked within the context of (automated) testing.

import unittestfrom viktor.testing import mock_Viewfrom app.my_entity_type.controller import MyEntityTypeControllerclass TestMyEntityTypeController(unittest.TestCase):    @mock_View(MyEntityTypeController)    def test_web_view(self):        params = ...        result = MyEntityTypeController().web_view(params=params)        self.assertEqual(result.html, ...)