WIP load_template plugin hook, refs #1042

load-template-plugin-hook
Simon Willison 2020-10-24 11:27:23 -07:00
rodzic d3e9b0aecb
commit 5b4e4ab434
3 zmienionych plików z 39 dodań i 6 usunięć

Wyświetl plik

@ -49,6 +49,11 @@ def extra_template_vars(
"Extra template variables to be made available to the template - can return dict or callable or awaitable"
@hookspec
def load_template(template, database, table, columns, view_name, request, datasette):
"Load the specified template, returning the template code as a string"
@hookspec
def publish_subcommand(publish):
"Subcommands for 'datasette publish'"

Wyświetl plik

@ -45,6 +45,10 @@
<script>{{ body_script }}</script>
{% endfor %}
{% if select_templates %}<!-- Templates considered: {{ select_templates|join(", ") }} -->{% endif %}
{% if templates_considered %}
<!-- Templates considered:
{% for template in templates_considered %}{{ template.name }}{% if template.used %} (used){% endif %}
{% endfor %}-->
{% endif %}
</body>
</html>

Wyświetl plik

@ -113,15 +113,39 @@ class BaseView:
async def render(self, templates, request, context=None):
context = context or {}
template = self.ds.jinja_env.select_template(templates)
# Give plugins first chance at loading the template
break_outer = False
plugin_template_source = None
template_name = None
for template_name in templates:
if break_outer:
break
for plugin_template_source in pm.hook.load_template(
template=template_name,
database=context.get("database"),
table=context.get("table"),
columns=context.get("columns"),
view_name=self.name,
request=request,
datasette=self.ds,
):
plugin_template_source = await await_me_maybe(plugin_template_source)
if plugin_template_source:
break_outer = True
break
if plugin_template_source is not None:
template = self.ds.jinja_env.from_string(plugin_template_source)
else:
template = self.ds.jinja_env.select_template(templates)
template_context = {
**context,
**{
"database_color": self.database_color,
"select_templates": [
"{}{}".format(
"*" if template_name == template.name else "", template_name
)
"templates_considered": [{
"name": template.name,
"used": template_name == template.name
}
for template_name in templates
],
},