1

When creating an HTML widget in FreeBoard, the following text is displayed:

Can be literal HTML, or javascript that outputs HTML.

I know I can do the following to return HTML with data, but if I want to do something more complex I'd prefer to use literal HTML

return html with data

return "<div style='color: red'>This is a red timestamp: " + datasources["DS"]["Timestamp"] + "</div>"

literal html with no data

<div style='color: red'>
  This is red text.
</div>
<div style='color: blue'>
  This is blue text.
</div>

Both of those work. My question is, how can I insert data from a datasource into the literal html example?

For more context, here is what is at the top of the editor:

This javascript will be re-evaluated any time a datasource referenced here is updated, and the value you return will be displayed in the widget. You can assume this javascript is wrapped in a function of the form function(datasources) where datasources is a collection of javascript objects (keyed by their name) corresponding to the most current data in a datasource.

And here is the default text:

// Example: Convert temp from C to F and truncate to 2 decimal places.
// return (datasources["MyDatasource"].sensor.tempInF * 1.8 + 32).toFixed(2);

2 Answers2

0

I don't know the freeboard framework, but a generic solution would be to use HTML5 templates, if your browser support requirements allow it.

function supportsTemplate() {
  return 'content' in document.createElement('template');
}

if (supportsTemplate()) {
  alert('browser supports templates');
} else {
  alert('browser does not support templates');
}

var template = document.querySelector('#timestamp-template');

var timestamp = template.content.querySelector('.timestamp');
timestamp.innerHTML = new Date().toLocaleString();

var clone = document.importNode(template.content, true);

var output = document.querySelector('#output');
output.appendChild(clone);
<template id="timestamp-template">
  <div style='color: red' class="timestamp">
    This is default red text.
  </div>
  <div style='color: blue'>
    This is blue text.
  </div>
</template>


<div id="output"></div>

You would obviously need to adapt this strategy to support whatever data sources and transforms your project needs.

Failing support for HTML5 template elements, you could also use <script type="text/template">.

Palpatim
  • 9,074
  • 35
  • 43
-2

Here is an example of how to insert a Datasource into an HTML widget:

var LVL = datasources["GL"]["Level"];
return `<div style="width: 200px; height: 200px;background:rgb(242,203,56);"></style>
<svg width=200 height=`+LVL+`><rect width=100% height=100% fill=grey></svg>
</div>`;