{
 "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. However most users can avoid modifying the jinja2 template directly by using one of the default templates shipped with Panel itself."
   ]
  },
  {
   "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(sizing_mode='stretch_width')"
   ]
  },
  {
   "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, instead 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 four 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",
    "* **`modal`**: A modal, i.e. a dialog box/popup window\n",
    "\n",
    "These four 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",
    "\n",
    "<img src=\"../assets/template_areas.png\" style=\"margin-left: auto; margin-right: auto; display: block;\"></img>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Supported templates\n",
    "\n",
    "Panel ships with a number of these default themes built on different CSS frameworks:\n",
    "    \n",
    "* **[``MaterialTemplate``](../reference/templates/Material.ipynb)**: Built on [Material Components for the web](https://material.io/develop/web/)\n",
    "* **[``BootstrapTemplate``](../reference/templates/Bootstrap.ipynb)**: Built on  [Bootstrap v4](https://getbootstrap.com/docs/4.0/getting-started/introduction/)\n",
    "* **[``VanillaTemplate``](../reference/templates/Vanilla.ipynb)**: Built using pure CSS without relying on any specific framework\n",
    "* **[``FastListTemplate``](../reference/templates/FastListTemplate.ipynb)**: Built on the [Fast UI](https://fast.design/) framework using a list-like API\n",
    "* **[``FastGridTemplate``](../reference/templates/FastGridTemplate.ipynb)**: Built on the [Fast UI](https://fast.design/) framework using grid-like API\n",
    "* **[``GoldenTemplate``](../reference/templates/GoldenLayout.ipynb)**: Built on the [Golden Layout](https://golden-layout.com/) framework"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Using templates\n",
    "\n",
    "There are two ways of building an application using these templates either we explicitly construct the template or we change the global template.\n",
    "\n",
    "#### Explicit constructor\n",
    "\n",
    "The explicit way to use templates is to instantiate them directly and adding components to the different parts of the template directly. 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",
    "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": [
    "<div style=\"margin: auto 0;\">\n",
    "<figure>\n",
    "<img src=\"../assets/template.png\"></img>\n",
    "    <caption><b>Bootstrap Template</b>: A simple example demonstrating the Bootstrap template</caption>\n",
    "</figure>\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": [
    "### Global template\n",
    "\n",
    "Another, often simpler approach is to set the global template can be set via the `pn.extension()` call, e.g. we can set `pn.extension(template='material')` and even toggle between different themes with `pn.extension(template='material', theme='dark')`. Once selected we can easily add components to the template using `.servable(area=...)` calls, e.g. the same example looks like this when constructed via the global template\n",
    "\n",
    "```python\n",
    "pn.extension(template='bootstrap')\n",
    "\n",
    "freq = pn.widgets.FloatSlider(name=\"Frequency\", start=0, end=10, value=2).servable(area='sidebar')\n",
    "phase = pn.widgets.FloatSlider(name=\"Phase\", start=0, end=np.pi).servable(area='sidebar')\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",
    "pn.Row(\n",
    "    pn.Card(hv.DynamicMap(sine), title='Sine'),\n",
    "    pn.Card(hv.DynamicMap(cosine), title='Cosine')\n",
    ").servable(area='main') # Note 'main' is the default\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Modal\n",
    "\n",
    "A modal can be toggled opened and closed with `.open_modal()` and `.close_modal()` methods. For example, a temporary *About* modal could be added to the previous app with:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import time\n",
    "\n",
    "# Callback that will be called when the About button is clicked\n",
    "def about_callback(event):\n",
    "    bootstrap.open_modal()\n",
    "    time.sleep(10)\n",
    "    bootstrap.close_modal()\n",
    "\n",
    "# Create, link and add the button to the sidebar\n",
    "btn = pn.widgets.Button(name=\"About\")\n",
    "btn.on_click(about_callback)\n",
    "bootstrap.sidebar.append(btn)\n",
    "\n",
    "# Add some content to the modal\n",
    "bootstrap.modal.append(\"# About...\")"
   ]
  },
  {
   "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 to use (e.g. `DarkTheme`) which loads the specific theme implementation (e.g. `MaterialDarkTheme`) for a particular `Template` (e.g `MaterialTemplate`). 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": [
    "<div style=\"margin: auto 0;\">\n",
    "<figure>\n",
    "<img src=\"../assets/dark_theme.png\"></img>\n",
    "    <caption><b>Dark Theme</b>: The MaterialTemplate with a DarkTheme applied</caption>\n",
    "</figure>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Using custom templates\n",
    "\n",
    "Completely custom templates extend the default jinja2 template in various ways. Before we dive into modifying such a template let us take a look at the default template used by Panel:\n",
    "\n",
    "```html\n",
    "{% from macros import embed %}\n",
    "\n",
    "<!DOCTYPE html>\n",
    "<html lang=\"en\">\n",
    "{% block head %}\n",
    "<head>\n",
    "    {% block inner_head %}\n",
    "    <meta charset=\"utf-8\">\n",
    "    <title>{% block title %}{{ title | e if title else \"Panel App\" }}{% endblock %}</title>\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",
    "</head>\n",
    "{% endblock %}\n",
    "{% block body %}\n",
    "<body>\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",
    "</body>\n",
    "{% endblock %}\n",
    "</html>\n",
    "```\n",
    "\n",
    "As you may be able to note if you are familiar with jinja2 templating or similar languages, this template can easily be extended by overriding the existing `{% block ... %}` definitions. However it is also possible to completely override this default template instead.\n",
    "\n",
    "That said 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",
    "<!-- goes in body -->\n",
    "{% block postamble %}\n",
    "<link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\">\n",
    "{% endblock %}\n",
    "\n",
    "<!-- goes in body -->\n",
    "{% block contents %}\n",
    "{{ app_title }}\n",
    "<p>This is a Panel app with a custom template allowing us to compose multiple Panel objects into a single HTML document.</p>\n",
    "<br>\n",
    "<div class=\"container\">\n",
    "  <div class=\"row\">\n",
    "    <div class=\"col-sm\">\n",
    "      {{ embed(roots.A) }}\n",
    "    </div>\n",
    "    <div class=\"col-sm\">\n",
    "      {{ embed(roots.B) }}\n",
    "    </div>\n",
    "  </div>\n",
    "</div>\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', '<h1>Custom Template App</h1>')\n",
    "\n",
    "tmpl.add_panel('A', hv.Curve([1, 2, 3]))\n",
    "tmpl.add_panel('B', hv.Curve([1, 2, 3]))\n",
    "\n",
    "tmpl"
   ]
  },
  {
   "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",
    "<p>This is a Panel app with a custom template allowing us to compose multiple Panel objects into a single HTML document.</p>\n",
    "<br>\n",
    "<div style=\"display:table; width: 100%\">\n",
    "  <div style=\"display:table-cell; margin: auto\">\n",
    "    {{ embed(roots.A) }}\n",
    "  </div>\n",
    "  <div style=\"display:table-cell; margin: auto\">\n",
    "    {{ embed(roots.B) }}\n",
    "  </div>\n",
    "</div>\n",
    "{% endblock %}\n",
    "\"\"\"\n",
    "\n",
    "tmpl = pn.Template(template, nb_template=nb_template)\n",
    "\n",
    "tmpl.add_variable('app_title', '<h1>Custom Template App</h1>')\n",
    "\n",
    "tmpl.add_panel('A', hv.Curve([1, 2, 3]))\n",
    "tmpl.add_panel('B', hv.Curve([1, 2, 3]))\n",
    "\n",
    "tmpl"
   ]
  },
  {
   "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]))\n",
    "tmpl.servable()"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python",
   "pygments_lexer": "ipython3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
