Skip to content

Commit

Permalink
fix: add safe filter
Browse files Browse the repository at this point in the history
  • Loading branch information
learosema committed Sep 30, 2024
1 parent 02b6416 commit ab97238
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
2 changes: 1 addition & 1 deletion demo/_layouts/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
<body>
<html-include src="header.html"/>
<main>
{{ content }}
{{ content | safe }}
</main>
<html-include src="footer.html"/>
</body>
Expand Down
19 changes: 16 additions & 3 deletions src/transforms/template-data.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,14 @@ const TEMPLATE_REGEX = /\{\{\s*([\w\.\[\]]+)(?:\((.*)\))?(?:\s*\|\s([a-zA-Z*]\w*
const JSON_PATH_REGEX = /^[a-zA-Z_]\w*((?:\.\w+)|(?:\[\d+\]))*$/
const JSON_PATH_TOKEN = /(^[a-zA-Z_]\w*)|(\.[a-zA-Z_]\w*)|(\[\d+\])/g

function mergeMaps(map1, map2) {
return new Map([...map1, ...map2]);
}

function htmlEscape(input) {
return input?.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}

/**
* Poor girl's jsonpath
*
Expand Down Expand Up @@ -59,7 +67,11 @@ export function parseArguments(args, data) {
* @returns {(data: any, filters: Map<string, function>) => string} a function that takes a data object and returns the processed template
*/
export function template(str) {
return (data, filters) => {
const defaultFilters = new Map();
let isSafe = false;
defaultFilters.set('safe', (input) => { isSafe = true; return input; })
return (data, providedFilters) => {
const filters = mergeMaps(defaultFilters || new Map(), providedFilters || new Map())
return str.replace(TEMPLATE_REGEX, (_, expr, params, filter, filterParams) => {
let result = dataPath(expr)(data);
const args = parseArguments(params, data);
Expand All @@ -73,7 +85,7 @@ export function template(str) {
const filterArgs = parseArguments(filterParams, data);
result = filters.get(filter)(result, ...filterArgs);
}
return result;
return isSafe ? result : htmlEscape(result);
});
}
}
Expand Down Expand Up @@ -123,11 +135,12 @@ export async function handleTemplateFile(config, data, inputFile) {
const l = await handleTemplateFile(config,
{...fileData, content: fileContent, layout: null}, layoutFilePath);
if (l) {
fileContent = l.content;;
fileContent = l.content;
} else {
throw new Error('Layout not found:' + layoutFilePath);
}
}

return {content: fileContent, filename: outputFile};
}

0 comments on commit ab97238

Please sign in to comment.