{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "When deploying a Panel app or dashboard as a Bokeh application, it is rendered into a default template that serves the JS and CSS resources as well as the actual Panel object being shown. However, it is often desirable to customize the layout of the deployed app, or even to embed multiple separate panels into an app. The ``Template`` component in Panel allows customizing this default template, including the ability to rendering multiple components in a single document easily.\n", "\n", "## What is a template?\n", "\n", "A template is defined using the [Jinja2](http://jinja.pocoo.org/docs/) templating language, which makes it straightforward to extend the default template in various ways or even replace it entirely. Before modifying the default template, let us take a look at it in its entirety:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```html\n", "{% from macros import embed %}\n", "\n", "\n", "\n", "{% block head %}\n", "\n", " {% block inner_head %}\n", " \n", " {% block title %}{{ title | e if title else \"Panel App\" }}{% endblock %}\n", " {% block preamble %}{% endblock %}\n", " {% block resources %}\n", " {% block css_resources %}\n", " {{ bokeh_css | indent(8) if bokeh_css }}\n", " {% endblock %}\n", " {% block js_resources %}\n", " {{ bokeh_js | indent(8) if bokeh_js }}\n", " {% endblock %}\n", " {% endblock %}\n", " {% block postamble %}{% endblock %}\n", " {% endblock %}\n", "\n", "{% endblock %}\n", "{% block body %}\n", "\n", " {% block inner_body %}\n", " {% block contents %}\n", " {% for doc in docs %}\n", " {{ embed(doc) if doc.elementid }}\n", " {% for root in doc.roots %}\n", " {{ embed(root) | indent(10) }}\n", " {% endfor %}\n", " {% endfor %}\n", " {% endblock %}\n", " {{ plot_script | indent(8) }}\n", " {% endblock %}\n", "\n", "{% endblock %}\n", "\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As we can see the template defines a number of custom blocks, which can be overridden by extending this default template." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import panel as pn\n", "import numpy as np\n", "import holoviews as hv\n", "\n", "pn.extension()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Using default templates\n", "\n", "For a large variety of use cases we do not need complete control over the exact layout of each individual component on the page we just want to achieve a more polished look and feel. For these cases Panel ships with a number of default templates, which are defined by declaring three main content areas on the page, which can be populated as desired:\n", "\n", "* **`header`**: The header area of the HTML page\n", "* **`sidebar`**: A collapsible sidebar\n", "* **`main`**: The main area of the application\n", "\n", "These three areas behave very similarly to other Panel layout components and have list-like semantics. This means we can easily append new components into these areas. Unlike other layout components however, the contents of the areas is fixed once rendered. If you need a dynamic layout you should therefore insert a regular Panel layout component (e.g. a `Column` or `Row`) and modify it in place once added to one of the content areas. \n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Supported themes\n", "\n", "Panel ships with a number of these default themes built on different CSS frameworks:\n", " \n", "* `MaterialTemplate`: Built on [Material Components for the web](https://material.io/develop/web/)\n", "* `BootstrapTemplate`: Built on [Bootstrap v4](https://getbootstrap.com/docs/4.0/getting-started/introduction/)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let us construct a very simple app containing two plots in the `main` area and two widgets in the sidebar based on the `BootstrapTemplate` class:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "bootstrap = pn.template.BootstrapTemplate(title='Bootstrap Template')\n", "\n", "pn.config.sizing_mode = 'stretch_width'\n", "\n", "xs = np.linspace(0, np.pi)\n", "freq = pn.widgets.FloatSlider(name=\"Frequency\", start=0, end=10, value=2)\n", "phase = pn.widgets.FloatSlider(name=\"Phase\", start=0, end=np.pi)\n", "\n", "@pn.depends(freq=freq, phase=phase)\n", "def sine(freq, phase):\n", " return hv.Curve((xs, np.sin(xs*freq+phase))).opts(\n", " responsive=True, min_height=400)\n", "\n", "@pn.depends(freq=freq, phase=phase)\n", "def cosine(freq, phase):\n", " return hv.Curve((xs, np.cos(xs*freq+phase))).opts(\n", " responsive=True, min_height=400)\n", "\n", "bootstrap.sidebar.append(freq)\n", "bootstrap.sidebar.append(phase)\n", "\n", "bootstrap.main.append(\n", " pn.Row(\n", " pn.Card(hv.DynamicMap(sine), title='Sine'),\n", " pn.Card(hv.DynamicMap(cosine), title='Cosine')\n", " )\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "
\n", "\n", " Bootstrap Template: A simple example demonstrating the Bootstrap template\n", "
\n", "\n", "A `Template` can be served or displayed just like any other Panel component, i.e. using `.servable()` or `.show()`." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Theming\n", "\n", "Default template classes provide a unified approach to theming, which currently allow specifying custom CSS and the Bokeh `Theme` to apply to the `Template`. The way it is implemented a user declares a generic `Theme` class and the `Template` loads the specific implementation for a particular `Template`. To make this more concrete, by default a Template uses the `DefaultTheme`, but then uses the `find_theme` method to look up the implementation of that theme for the Template being used:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from panel.template import DefaultTheme\n", "\n", "DefaultTheme.find_theme(pn.template.MaterialTemplate)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To implement your own theme you should therefore declare a generic class for use by the enduser and a specific implementation for all the themes that should be supported, e.g. here is an example of what the definition of a dark theme might look like:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import param\n", "\n", "from panel.template.theme import Theme\n", "from bokeh.themes import DARK_MINIMAL\n", "\n", "class DarkTheme(Theme):\n", " \"\"\"\n", " The DarkTheme provides a dark color palette\n", " \"\"\"\n", "\n", " bokeh_theme = param.ClassSelector(class_=(Theme, str), default=DARK_MINIMAL)\n", "\n", "class MaterialDarkTheme(DarkTheme):\n", "\n", " # css = param.Filename() Here we could declare some custom CSS to apply\n", " \n", " # This tells Panel to use this implementation\n", " _template = pn.template.MaterialTemplate" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To apply the theme we now merely have to provide the generic `DarkTheme` class to the Template (we will import the `DarkTheme` that ships with panel here:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from panel.template import DarkTheme\n", "\n", "dark_material = pn.template.MaterialTemplate(title='Material Template', theme=DarkTheme)\n", "\n", "dark_material.sidebar.append(freq)\n", "dark_material.sidebar.append(phase)\n", "\n", "dark_material.main.append(\n", " pn.Row(\n", " pn.Card(hv.DynamicMap(sine), title='Sine'),\n", " pn.Card(hv.DynamicMap(cosine), title='Cosine')\n", " )\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "
\n", "\n", " Dark Theme: The MaterialTemplate with a DarkTheme applied\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Using custom templates" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Once we have loaded Panel we can start defining a custom template. As mentioned before, it is usually easiest to simply extend an existing template by overriding certain blocks. To begin with we start by using `{% extends base %}` to declare that we are merely extending an existing template rather than defining a whole new one; otherwise we would have to repeat the entire header sections of the full template to ensure all the appropriate resources are loaded.\n", "\n", "In this case we will extend the postamble block of the header to load some additional resources, and the contents block to redefine how the components will be laid out. Specifically, we will load bootstrap.css in the preamble allowing us to use the bootstrap grid system to lay out the output." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "template = \"\"\"\n", "{% extends base %}\n", "\n", "\n", "{% block postamble %}\n", "\n", "{% endblock %}\n", "\n", "\n", "{% block contents %}\n", "{{ app_title }}\n", "

This is a Panel app with a custom template allowing us to compose multiple Panel objects into a single HTML document.

\n", "
\n", "
\n", "
\n", "
\n", " {{ embed(roots.A) }}\n", "
\n", "
\n", " {{ embed(roots.B) }}\n", "
\n", "
\n", "
\n", "{% endblock %}\n", "\"\"\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you look closely we defined two different roots in the template using the `embed` macro. In order to be able to render the template we now have to first construct the `pn.Template` object with the template HTML and then populate the template with the two required roots, in this case `'A'` and `'B'` by using the `add_panel` method. If either of the roots is not defined the app is invalid and will fail to launch. The app will also fail to launch if any panels are added that are not referenced in the template.\n", "\n", "Additionally we have also declared a new `app_title` variable in the template, which we can populate by using the `add_variable` method:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "tmpl = pn.Template(template)\n", "\n", "tmpl.add_variable('app_title', '

Custom Template App

')\n", "\n", "tmpl.add_panel('A', hv.Curve([1, 2, 3]))\n", "tmpl.add_panel('B', hv.Curve([1, 2, 3]))\n", "\n", "tmpl.servable();" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Embedding a different CSS framework (like Bootstrap) in the notebook can have undesirable side-effects so a `Template` may also be given a separate `nb_template` that will be used when rendering inside the notebook:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "nb_template = \"\"\"\n", "{% extends base %}\n", "\n", "{% block contents %}\n", "{{ app_title }}\n", "

This is a Panel app with a custom template allowing us to compose multiple Panel objects into a single HTML document.

\n", "
\n", "
\n", "
\n", " {{ embed(roots.A) }}\n", "
\n", "
\n", " {{ embed(roots.B) }}\n", "
\n", "
\n", "{% endblock %}\n", "\"\"\"\n", "\n", "tmpl = pn.Template(template, nb_template=nb_template)\n", "\n", "tmpl.add_variable('app_title', '

Custom Template App

')\n", "\n", "tmpl.add_panel('A', hv.Curve([1, 2, 3]))\n", "tmpl.add_panel('B', hv.Curve([1, 2, 3]))\n", "\n", "tmpl.servable()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Loading template from file\n", "\n", "If the template is larger it is often cleaner to define it in a separate file. You can either read it in as a string, or use the official loading mechanism available for Jinja2 templates by defining a `Environment` along with a `loader`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from jinja2 import Environment, FileSystemLoader\n", "\n", "env = Environment(loader=FileSystemLoader('.'))\n", "jinja_template = env.get_template('sample_template.html')\n", "\n", "tmpl = pn.Template(jinja_template)\n", "\n", "tmpl.add_panel('A', hv.Curve([1, 2, 3]))\n", "tmpl.add_panel('B', hv.Curve([1, 2, 3]))" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.5" }, "widgets": { "application/vnd.jupyter.widget-state+json": { "state": {}, "version_major": 2, "version_minor": 0 } } }, "nbformat": 4, "nbformat_minor": 4 }