i have a backend service that I wrote in Golang
, something like this:
func PageA_RequestHandler(ctx *W.Context) {
// init things
if is_ajax {
// handle the API request, render the JSON
return
}
// query the initial rows
values := M.SX{
`rows`: model1.GetRows(10),
`columns`: model1.GetColumns(),
}
// render the html
ctx.Render(`page_a_template`,values)
}
then the template file page_a_template.html
(that loaded and cached at the first time it rendered), is a html file, with content something like this:
<div id="grid"></div>
<script>
var rows = {/* rows */};
var cols = [/* columns */]
new GridBuilder('grid',cols,rows);
</script>
Where's:
{/* rows */}
and [/* columns */]
are my javascript-friendly template syntax, there are some other syntax like: /*! bar */
or #{yay}
new GridBuilder
is my custom javascript component that creates something like datatables.net
or editablegrid.net
The question is, if I use Elm
, what's the correct way to inject the {/* rows */}
into the compiled html?
Use Html.programWithFlags (supposing your main module is named App
):
<div id="grid"></div>
<script>
var rows = {/* rows */};
var cols = [/* columns */];
var node = document.getElementById('grid');
Elm.App.embed(node, { rows: rows, cols: cols });
</script>
This is the way you can initialize your Elm app with available data just like you are initializing GridBuilder
.
To be able to read those values, you should create a Flags
type alias and your init
function will receive it.
type alias Flags =
{ rows : [ ... ]
, cols : [ ... ]
}
init : Flags -> ( Model, Cmd Msg )
init flags =
...
Your main
function will look like this:
main =
Html.programWithFlags
{ init = init, ... }
I highly recommend that you read the JavaScript Interop section of the Elm Guide. It explains the programWithFlags
and other approaches to receive/send data from/to JavaScript.