Html

I like using the string declaration for html using the = @"…" and then the multiple lines are much clearer for editing. How can I insert dynamic values into the string?
local html = @" <!DOCTYPE html><html lang='en'> <body> ...dynamic variable here.... </body> </html> "; return html;

You have a few options here depending on what you want to do:

If you want the page to dynamically update itself without having to refresh the page, you’ll need to use some Javascript + AJAX. You can learn more about that in a somewhat recently posted article on our Community Blog.

If you want to render the webpage using the current values of some variables (i.e. when someone browses to the webpage it will load the page with whatever value the agent is currently storing) you can setup your HTML as a format string. Here’s a really simple example of how I might setup something like this:

`temp <- 32.5;
message <- “Hello World”;

function renderIndex() {
local html = @“


Web Page


Temperature


%0.2f degrees C

Last Message


%s


”;
return format(html, temp, message);

}

http.onrequest(function(req, resp) {
resp.send(200, renderIndex());
})`

This is a really basic example that doesn’t try to do anything to make things look pretty, but hopefully it makes what we’re doing clear…

Inside the html variable (in the renderIndex function) we have two format placeholders

The first is %0.2f, which tells the format method to replace that placeholder with a floating point number with two decimal points.

The second is %s, which tells the format method to replace that placeholder with a string.

fwiw, I tend to serve static HTML and static JS from my agent. Then I define another endpoint that returns JSON. I then run that through handlebars (on the browser) to render the dynamic HTML.

To make this easier, I have some natty Ruby scripts that inject external files into the agent squirrel as properly-escaped (or base64-encoded) strings. They look for //$asset and //$binary tags in the source.

I really should update them to talk to the new Build API, then I could make them public.