source: Klonkt/src/middleware/render.js@ 9e27d64

main
Last change on this file since 9e27d64 was 7bc636b, checked in by Robin <robin@…>, 4 months ago

Initial commit — PrutFolio v1 source (pulled from Hetzner /srv/prutfolio)

  • Property mode set to 100644
File size: 4.0 KB
RevLine 
[7bc636b]1/**
2 * Render helper — THE pattern for the entire app.
3 *
4 * Two modes:
5 * 1. HTMX request → render just the page content (no shell)
6 * 2. Full page request → render content, then embed in shell
7 *
8 * Usage:
9 * renderPage(req, res, 'pages/home', { posts, ...data })
10 */
11
12import path from 'path';
13import { fileURLToPath } from 'url';
14import ejs from 'ejs';
15import PermissionsService from '../services/PermissionsService.js';
16import { PLATFORMS as PLATFORMS_CATALOG } from '../services/PlatformIcons.js';
17
18const __dirname = path.dirname(fileURLToPath(import.meta.url));
19const VIEWS_DIR = path.join(__dirname, '..', 'views');
20
21const formatDate = (iso) => {
22 if (!iso) return '';
23 const d = new Date(iso);
24 const months = ['januari','februari','maart','april','mei','juni','juli','augustus','september','oktober','november','december'];
25 return `${d.getDate()} ${months[d.getMonth()]} ${d.getFullYear()}`;
26};
27
28const formatDateTime = (iso) => {
29 if (!iso) return '';
30 const d = new Date(iso);
31 return d.toLocaleString('nl-NL', { dateStyle: 'medium', timeStyle: 'short' });
32};
33
34export async function renderPage(req, res, viewName, data = {}) {
35 // Decide: partial (HTMX) or full?
36 const isPartial = req.headers['hx-request'] === 'true' || req.query.partial === '1';
37
38 // Common locals
39 const locals = {
40 user: req.session?.user || null,
41 site: data.site || res.locals.site || null,
42 audioTracks: data.audioTracks || res.locals.audioTracks || [],
43 siteUrlBase: res.locals.siteUrlBase || '',
44 platforms_catalog: PLATFORMS_CATALOG,
45 permissions: PermissionsService,
46 formatDate,
47 formatDateTime,
48 pageTitle: data.pageTitle || (data.site && data.site.title) || 'PrutCMS',
49 bodyClass: data.bodyClass || 'on-home',
50 socialDescr: data.socialDescr || '',
51 socialImage: data.socialImage || '',
52 cspNonce: () => '',
53 currentPath: req.path,
54 ...data,
55 };
56
57 try {
58 // Step 1: Render the page view to HTML
59 const viewPath = path.join(VIEWS_DIR, viewName + '.ejs');
60 const pageContent = await ejs.renderFile(viewPath, locals, { async: false });
61
62 if (isPartial) {
63 // HTMX: just send the content. Set HX-Trigger for body class swap
64 res.setHeader('HX-Trigger-After-Settle', JSON.stringify({
65 pcmsNav: { bodyClass: locals.bodyClass },
66 pcmsPostSwap: data.post ? {
67 title: data.post.title,
68 slug: data.post.slug,
69 pageTitle: locals.pageTitle,
70 } : null,
71 }));
72 return res.send(pageContent);
73 }
74
75 // Full: wrap content in shell
76 locals.pageContent = pageContent;
77 res.render('shell', locals);
78 } catch (err) {
79 console.error('[renderPage] Error rendering', viewName, err);
80 if (process.env.NODE_ENV === 'production') {
81 return res.status(500).send('Internal Server Error');
82 }
83 // Dev: surface the underlying cause prominently. EJS rewrites err.message
84 // to include the file/line/code-context, so we also surface name+stack
85 // separately in case the message was truncated or empty.
86 const escape = (s) => String(s == null ? '' : s)
87 .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
88 res.status(500).send(`<!doctype html>
89<meta charset="utf-8">
90<title>Render error: ${escape(viewName)}</title>
91<style>
92 body { font: 14px/1.5 ui-monospace, monospace; max-width: 1100px; margin: 2rem auto; padding: 0 1rem; background:#1a1a1a; color:#eee; }
93 h1 { color:#dc2626; font-family: ui-sans-serif, system-ui; }
94 h2 { color:#fb923c; font-size:1rem; margin-top:1.5rem; }
95 pre { background:#0a0a0a; border:1px solid #333; border-radius:6px; padding:1rem; overflow:auto; white-space:pre-wrap; word-break:break-word; }
96 .cause { background:#3d0a0a; border-color:#7a1a1a; color:#fca5a5; font-weight:600; }
97</style>
98<h1>Render error in ${escape(viewName)}</h1>
99<h2>Cause</h2>
100<pre class="cause">${escape(err.name || 'Error')}: ${escape(err.message || '(no message)')}</pre>
101<h2>Stack</h2>
102<pre>${escape(err.stack || '(no stack)')}</pre>
103${err.path ? `<h2>File</h2><pre>${escape(err.path)}</pre>` : ''}
104`);
105 }
106}
Note: See TracBrowser for help on using the repository browser.