baseddata.io/layouts/shortcodes/table.html

68 lines
2.2 KiB
HTML
Raw Normal View History

2024-09-10 09:15:00 +01:00
<script>
async function fetchDataForTable() {
try {
const apiEndpoint = `${apiURL}/{{ .Get "endpoint" }}`;
const response = await fetch(apiEndpoint);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const fetchedData = await response.json();
data = fetchedData;
console.log(data);
createTable(data);
} catch (error) {
console.error("Fetching data failed:", error);
}
}
function createTable(data) {
const jsonTableContainer = document.getElementById("jsonTableContainer");
jsonTableContainer.innerHTML = "";
jsonTableContainer.style.maxHeight = "{{ .Get `maxHeight` }}"
tableHeaderNames = Object.values({{ .Get `headers` | safeJS }});
tableHeaderKeys = Object.keys({{ .Get `headers` | safeJS }});
const table = document.createElement("table");
table.id = "{{ .Get `id` }}"
const thead = document.createElement("thead");
const tbody = document.createElement("tbody");
const headerRow = document.createElement("tr");
tableHeaderNames.forEach((header) => {
const th = document.createElement("th");
th.textContent = header;
headerRow.appendChild(th);
});
thead.appendChild(headerRow);
table.appendChild(thead);
for (const key in data) {
const row = document.createElement('tr');
tableHeaderKeys.forEach((columnName) => {
const td = document.createElement("td");
const div = document.createElement("div");
div.id = "scrollable";
if (columnName == "{{ .Get `tableKey` }}") {
div.textContent = key;
} else {
div.textContent = data[key][columnName];
};
td.appendChild(div);
row.appendChild(td);
tbody.appendChild(row);
});
}
table.appendChild(thead);
table.appendChild(tbody);
jsonTableContainer.appendChild(table)
{{ if eq (.Get "sortable") "true" }}
table.className = "sortable"
sorttable.makeSortable(document.getElementById("{{ .Get `id` }}"));
{{ end }}
table.className = ""
}
</script>
<div id="jsonTableContainer"></div>
<script src="/js/lib/sorttable.js"></script>