Skip to content

Commit 4e6172e

Browse files
committed
feat: add support for custom head HTML injection
Implement a mechanism to inject custom HTML (e.g., analytics scripts) into the <head> section via an optional extra_head.html file. The file is cached after first read to avoid repeated I/O operations.
1 parent 8410980 commit 4e6172e

3 files changed

Lines changed: 36 additions & 0 deletions

File tree

.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,3 +40,6 @@ coverage.xml
4040

4141
# Sphinx documentation
4242
docs/_build/
43+
44+
# Deployment-specific extra head HTML (e.g. analytics scripts)
45+
extra_head.html

ckanext/digitizationknowledge/helpers.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,11 @@
33
import ckan.authz as authz
44
from sqlalchemy import and_, not_, exists
55
from typing import Any
6+
import os
7+
import logging
8+
from functools import lru_cache
9+
10+
log = logging.getLogger(__name__)
611

712

813
def is_group_private(group):
@@ -156,10 +161,30 @@ def get_custom_featured_organizations(count: int = 1):
156161
return []
157162

158163

164+
@lru_cache(maxsize=1)
165+
def get_extra_head_html():
166+
"""
167+
Read extra HTML to inject in <head> from assets/extra_head.html.
168+
Content is cached after first read to avoid repeated file I/O.
169+
Returns empty string if the file doesn't exist.
170+
"""
171+
file_path = os.path.join(
172+
os.path.dirname(__file__), 'assets', 'extra_head.html'
173+
)
174+
try:
175+
with open(file_path, 'r', encoding='utf-8') as f:
176+
content = f.read()
177+
log.info('Loaded extra head HTML from %s', file_path)
178+
return content
179+
except FileNotFoundError:
180+
log.debug('No extra head HTML file at %s', file_path)
181+
return ''
182+
159183
def get_helpers():
160184
return {
161185
"get_custom_featured_groups": get_custom_featured_groups,
162186
"get_custom_featured_organizations": get_custom_featured_organizations,
163187
"is_group_private": is_group_private,
164188
"user_can_view_group": user_can_view_group,
189+
"get_extra_head_html": get_extra_head_html,
165190
}

ckanext/digitizationknowledge/templates/base.html

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,12 @@
44
{{ super() }}
55
{% asset 'digitizationknowledge_theme/main-css' %}
66
<script src="//unpkg.com/alpinejs" defer></script>
7+
{% endblock %}
8+
9+
{% block head_extras %}
10+
{{ super() }}
11+
{% set extra_head_html = h.get_extra_head_html() %}
12+
{% if extra_head_html %}
13+
{{ extra_head_html | safe }}
14+
{% endif %}
715
{% endblock %}

0 commit comments

Comments
 (0)