'Insert javaScript function inside FreeMarker template
I have a problem introducing a js function inside ftl.
I have a javaScript function which converts a value from bytes to kilobytes, on the other side I need to call that function in ftl. I am using script tag, but when I want to assign the calculated value and print it, I get nothing.
This is my js function:
function formatBytes(bytes, decimals = 0) {
if (bytes === 0) return "0 Bytes";
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + " " + sizes[i];
}
And this is the way how I tried to call it inside ftl:
<span class="inner">
<span class="label">Size:</span>
<span class="value">
<#assign size = node.size>
<#assign sizeInBytes = size>
<script>
<#assign result = "" >
result = formatBytes(${sizeInBytes?replace(",", "", "r")});
</script>
${result}
</span>
I tried also this:
<span class="value">
<#assign size = node.size>
<#assign sizeInBytes = size>
<script>
<#assign result = formatBytes('${sizeInBytes?replace(",", "", "r")}') >
</script>
${result}
</span>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|