Add template renderer for extensions

This commit is contained in:
Cohee 2023-08-25 20:34:26 +03:00
parent 91d13efcef
commit b32a085e41
2 changed files with 17 additions and 4 deletions

View File

@ -496,9 +496,10 @@ function getUrlSync(url, cache = true) {
}).responseText;
}
function renderTemplate(templateId, templateData = {}, sanitize = true, localize = true) {
export function renderTemplate(templateId, templateData = {}, sanitize = true, localize = true, fullPath = false) {
try {
const templateContent = getUrlSync(`/scripts/templates/${templateId}.html`);
const pathToTemplate = fullPath ? templateId : `/scripts/templates/${templateId}.html`;
const templateContent = getUrlSync(pathToTemplate);
const template = Handlebars.compile(templateContent);
let result = template(templateData);

View File

@ -1,5 +1,5 @@
import { callPopup, eventSource, event_types, saveSettings, saveSettingsDebounced, getRequestHeaders, substituteParams } from "../script.js";
import { isSubsetOf, debounce, waitUntilCondition } from "./utils.js";
import { callPopup, eventSource, event_types, saveSettings, saveSettingsDebounced, getRequestHeaders, substituteParams, renderTemplate } from "../script.js";
import { isSubsetOf } from "./utils.js";
export {
getContext,
getApiUrl,
@ -48,6 +48,18 @@ export function saveMetadataDebounced() {
export const extensionsHandlebars = Handlebars.create();
/**
* Provides an ability for extensions to render HTML templates.
* Templates sanitation and localization is forced.
* @param {string} extensionName Extension name
* @param {string} templateId Template ID
* @param {object} templateData Additional data to pass to the template
* @returns {string} Rendered HTML
*/
export function renderExtensionTemplate(extensionName, templateId, templateData = {}, sanitize = true, localize = true) {
return renderTemplate(`scripts/extensions/${extensionName}/${templateId}.html`, templateData, sanitize, localize, true);
}
/**
* Registers a Handlebars helper for use in extensions.
* @param {string} name Handlebars helper name