fallback to default HTML template if custom template does not exist (#604)

* fallback to default HTML template if custom template does not exist

* add docs
This commit is contained in:
Tom Kralidis
2021-01-11 15:15:47 -05:00
committed by GitHub
parent e9079a1b3d
commit fc6fd9d86f
2 changed files with 20 additions and 1 deletions
+6
View File
@@ -18,6 +18,12 @@ The default pygeoapi configuration has ``server.templates`` commented out and de
Your templates folder should mimic the same file names and structure of the default pygeoapi templates. Otherwise, you will need to modify ``api.py`` accordingly.
Note that you need only copy and edit the templates you are interested in updating. For example,
if you are only interested in updating the ``landing_page.html`` template, then create your own version
of the only that same file. When pygeoapi detects that a custom HTML template is being used,
it will look for the custom template in ``server.templates.path``. If it does not exists, pygeoapi
will render the default HTML template for the given endpoint/requuest.
Linking to a static file in your HTML templates can be done using Jinja syntax and the exposed ``config['server']['url']``:
.. code-block:: html
+14 -1
View File
@@ -44,6 +44,7 @@ from urllib.parse import urlparse
import dateutil.parser
from jinja2 import Environment, FileSystemLoader
from jinja2.exceptions import TemplateNotFound
import yaml
from pygeoapi import __version__
@@ -265,9 +266,11 @@ def render_j2_template(config, template, data):
:returns: string of rendered template
"""
custom_templates = False
try:
templates_path = config['server']['templates']['path']
env = Environment(loader=FileSystemLoader(templates_path))
custom_templates = True
LOGGER.debug('using custom templates: {}'.format(templates_path))
except (KeyError, TypeError):
env = Environment(loader=FileSystemLoader(TEMPLATES))
@@ -287,7 +290,17 @@ def render_j2_template(config, template, data):
env.filters['filter_dict_by_key_value'] = filter_dict_by_key_value
env.globals.update(filter_dict_by_key_value=filter_dict_by_key_value)
template = env.get_template(template)
try:
template = env.get_template(template)
except TemplateNotFound as err:
if custom_templates:
LOGGER.debug(err)
LOGGER.debug('Custom template not found; using default')
env = Environment(loader=FileSystemLoader(TEMPLATES))
template = env.get_template(template)
else:
raise
return template.render(config=config, data=data, version=__version__)