Skip to content

Commit

Permalink
Format files, add example template, and optimise code.
Browse files Browse the repository at this point in the history
  • Loading branch information
EarthlingDavey committed Oct 17, 2024
1 parent 5ca45ec commit c23c3d8
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 19 deletions.
42 changes: 24 additions & 18 deletions public/app/themes/clarity/src/globals/js/ajax-templating.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,24 @@
* @see https://stackoverflow.com/a/39065147/6671505
*
* @example
* Template:
* <script type="text/template" data-template="results-template">
* <div class="result">
* <h2>${title}</h2>
* <p>${content}</p>
* ${?imgSrc}
* <img src="${imgSrc}" alt="${title}" />
* ${/?imgSrc}
* </div>
*
* Implementation:
* const template = new AjaxTemplating("results-template");
* const html = template.renderHtml({
* title: "Hello World",
* content: "This is a test."
* content: "This is a test.",
* imgSrc: "https://example.com/image.jpg",
* });
*
*/

export default class AjaxTemplating {
Expand All @@ -19,23 +32,16 @@ export default class AjaxTemplating {
* @param {string} templateName
*/
constructor(templateName) {
this.resultsTemplate = this.loadTemplate(templateName);
}

/**
* Load the template from the DOM.
*
* Returns an array of strings where:
* - every odd index is a template variable
* - every even is a string of html text
*
* @param {string} templateName
* @returns {string[]}
*/

loadTemplate(templateName) {
// do this without jQuery
return document
/**
* The template from the DOM.
*
* An array of strings where:
* - every odd index is a template variable
* - every even is a string of html text
*
* @type {string[]}
*/
this.resultsTemplate = document
.querySelector(`script[data-template="${templateName}"]`)
.textContent.split(/\$\{(.+?)\}/g);
}
Expand Down
2 changes: 1 addition & 1 deletion public/app/themes/clarity/src/globals/js/ajax-utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ export const renderResults = ({
// If we are on a page greater than 1, focus on the first new result.
if (currentPage > 1) {
const index = (currentPage - 1) * resultsPerPage;
$("#content").children().eq(index).find('div.content a').focus();
$("#content").children().eq(index).find("div.content a").focus();
}
};

Expand Down

0 comments on commit c23c3d8

Please sign in to comment.