On Sun, 10 May 2015 20:47:14 GMT, dat wrote:
n00b question: what is the best practice to generate some js in the controller and send it down to the view template?
At the moment I'm relying on plain string concatenation
...
results ~= [format(
"[%s,%s],",
object.getTimestamp(),
object.getValue()
)];
...
string json_results = "[";
foreach(result; results) {
json_results ~= result;
}
json_results ~= "]";
and in the template
script.
data : !{json_results},
I'm sure there is a better way to do this but couldn't find any detail anywhere in vibe.d or jade docs.
Thanks,
dat
If it's just pure data like in the example, you can use the JSON serialization functionality to generate the JavaScript code: serializeToJsonString
struct Result { string timestamp, value; }
Result[] results = ...;
render!"template.dt"(results);
- import vibe.data.json;
script
var data = #{serializeToJsonString(results)};
If performance is (still) an issue, you could also do something like this, but this is undocumented behavior that might change over time (also this is just off the top of my head, so some details may be wrong):
- import vibe.data.json;
- import vibe.stream.wrapper;
script
var data = !{() { auto dst = StreamOutputRange(output__); serializeToJson(dst, results); return ""; } ()};
But this would avoid any dynamic memory allocation and basically directly write the JSON string to the network connection.