|
| 1 | +{{/* |
| 2 | +Shortcode: dynamic-block |
| 3 | +------------------------ |
| 4 | + |
| 5 | +This shortcode allows you to inject frequently changing content from a JSON file |
| 6 | +into your Hugo pages. It is designed for cases where some parts of a page (such as |
| 7 | +status, last update timestamps, or feature lists) need to be updated often without |
| 8 | +rebuilding the entire site. |
| 9 | + |
| 10 | +Usage example |
| 11 | + |
| 12 | + {{< dynamic-block contentPath="persist/path-to/file.json" jsonKey="timestamp" >}} |
| 13 | + |
| 14 | +Arguments |
| 15 | + |
| 16 | +- contentPath (string) |
| 17 | + Path to the JSON file relative to the site base URL (e.g. "persist/status.json"). |
| 18 | + In production, JSON must be served from https://developer.espressif.com/persist/... |
| 19 | + |
| 20 | +- jsonKey (string) |
| 21 | + The key within the JSON object whose value will be injected into the page. |
| 22 | + The content can be plain text, Markdown, or a special field. |
| 23 | + |
| 24 | +Special field handling |
| 25 | + |
| 26 | +- jsonKey = "timestamp" |
| 27 | + If the key is `"timestamp"`, the shortcode expects an ISO8601 date/time string. |
| 28 | + It is automatically converted into a localized, human-readable format: |
| 29 | + `DD Mon YYYY, HH:MM AM/PM` (using the en-GB locale). |
| 30 | + |
| 31 | +Other keys |
| 32 | + |
| 33 | +- Any other key is assumed to contain Markdown content. |
| 34 | + The Markdown is rendered to HTML before being injected. |
| 35 | + |
| 36 | +Error handling |
| 37 | + |
| 38 | +If the JSON file cannot be fetched or the key is not found, the shortcode will display |
| 39 | +an error message instead of the content. |
| 40 | +*/}} |
| 41 | + |
| 42 | +{{/* |
| 43 | +Toggle for local testing: set to true to load JSON locally from contentPath |
| 44 | +(relative to your index.md location). |
| 45 | +Leave false (default) to resolve via .Site.BaseURL (web mode). |
| 46 | +*/}} |
| 47 | +{{ $localMode := false }} <!-- change to true for local --> |
| 48 | + |
| 49 | + |
1 | 50 | {{ $uniqueID := .Get "jsonKey" | urlize }} <!-- Generate a unique ID --> |
2 | 51 | <span id="content-{{ $uniqueID }}">Loading...</span> |
3 | 52 |
|
4 | 53 | {{ $contentPath := .Get "contentPath" }} |
5 | 54 | {{ $jsonKey := .Get "jsonKey" }} |
6 | | -{{ $fullURL := printf "%s%s" .Site.BaseURL $contentPath }} |
| 55 | + |
| 56 | +{{/* Only build $fullURL in web mode */}} |
| 57 | +{{ $fullURL := "" }} |
| 58 | +{{ if not $localMode }} |
| 59 | + {{ $fullURL = printf "%s%s" .Site.BaseURL $contentPath }} |
| 60 | +{{ end }} |
7 | 61 |
|
8 | 62 | <script> |
9 | 63 | document.addEventListener("DOMContentLoaded", function () { |
10 | | - const url = '{{ $fullURL }}'; |
| 64 | + const url = '{{ if $localMode }}{{ $contentPath }}{{ else }}{{ $fullURL }}{{ end }}'; |
11 | 65 | const jsonKey = '{{ $jsonKey }}'; |
12 | 66 | const uniqueID = '{{ $uniqueID }}'; |
13 | 67 |
|
|
0 commit comments