Bootstrapping JSON data into Scala PlayFramework templates - json

Goal is to go from a Model/ViewModel written in Scala to raw JSON that can be bootstrapped into the view template so as to avoid making requests for the JSON data after the page load.
And example of what I've been playing around with but I haven't had much luck:
#(todos: play.api.libs.json.JsValue)
#import play.api.libs.json.Json
<html>
<head>...</head>
<body>...</body>
<script>
var todos = JSON.parse(' #Json.stringify(todos) ');
</script>
</html>
Basically its spitting out a lot of quoted text to the effect of:
[{"id":":"294858e2-c9eb-4f50-9eac-47b257573d83"}]
Haven't had much luck with Google or the PlayFramework docs so I'd love some help.

The Play template engine will escape any strings you render to HTML, which will thoroughly mangle your JSON.
To output it verbatim, do #Html(Json.stringify(todos)), as described here.

Related

Gatling HTML response

Below is my HTML response in Gatling. I am looking to extract the value of the url field. How do I do that?
script type="text/javascript" id="test">
var initialVars={ "context" : { "A": "XXXX", "B":"XXXXX"}, "u.d" : {"C":"ABC", "D":"FGH"}};
var z = {"desktop": {"Q": "12345"}, "q.d": {"F": "QQQ", "url": "A&B=345=hhh"}}
I'm afraid you'll have no choice but to use regular expressions here. HTML parsers such as Gatling's CSS selectors support won't be of any help as you're trying to capture some data in inlined JavaScript.
Then, your problem has nothing to do with being new to Scala or Gatling.
It's about using/learning Java regular expressions.
If you struggle, you should read the Java patterns documentation and try some online evaluator.
Once you have your regex figured out, use it to add a regex check in your Gatling test.
Thank you! I figured out most of it.. This is the part that I am trying to extract
transId=7a2cd0ada80a8285cd1234d144631e80&pzFromFrame
Following REGEX expression ([0-9]+[a-z]+) extracts 7a2cd0ada80a8285cd1234d144631e leaving 80. How to extract 7a2cd0ada80a8285cd1234d144631e80?

Inserting JSON into HTML via script tag - is this safe?

Using express framework -
I am loading an initial JSON state representation into my template that my react front end will rehydrate its initial state from, but I'm wondering if it is safe to do something like this -
<script type="text/javascript">
window.INIT_DATA = <%- initialState %>
</script>
The output of that if I view the page source might look something like this -
<script type="text/javascript">
window.INIT_DATA = {"recentImages": [ 11342, 11344, 11432 ], "lastOnline": "Yesterday"}
</script>
Is this safe to do? Are there any good practices to follow? Thanks
No, this is not safe. Suppose the initialState contains a string that looks like this:
"hello! </script><script>alert("PWND")</script>"
This will cause the embedded code to run. In other words: if the JSON you're embedding contains any user supplied strings you're opening the door to XSS attacks.
To prevent this, replace </ with <\/, and <!-- with <\!--. In JSON strings \/ and \! will be interpreted as a simple slash or exclamation mark, so this doesn't change the semantics of the JSON, but it will prevent the HTML parser from seeing a closing tag.
I don't see why this wouldn't be safe? However I suggest you don't store the variable in the window object; it is discouraged as the window is a global object.

Dynamic Rendering of Math Equations using MathJax in Angular 2

I am building a test engine where the backend code is ready however i am getting stuck with the frontend part.
In the frontend part made using Angular 2 (project setup using angular-cli) I got stuck while rendering the math equations. I am using mathjax and please check what part i am doing wrong.
Just to clarify, I am able to render the static math equations using typescript however when I take the html string from the backend that is through dynamic loading, it doesn't load properly.
Code:
index.html
Included following two scripts within head tag.
MathJax.Hub.Config({
tex2jax: {
inlineMath: [['$','$'], ['\\(','\\)']],
processEscapes: true
}
});
cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-
MML_HTMLorMML
math equation latex
\\(2x^2+9y^2=z^3\\)
exam.component.ts
If I use a string like this:
this.sample = "math equation latex";
and render this in the exam.component.html as {{sample}}, then it works fine. However when I use a http service and get the response, in that case the resulting string it not rendered properly.
Also I read the internet where I found a script to use for dynamic loading involving "typeset", but that doesn't work too.
Please point out what I am doing wrong. Thanks!

Creating a UI/writing HTML from a JSON file

I have a really long, unwieldy, unformatted JSON file generated by Lighthouse (a tool that conducts page load time analysis- so this file has the results of the tests). In order to make it formatted to be readable by people, I need to apparently create a UI around this file. My problem is that I'm not sure how to begin working on it.
I've read about something like creating HTML from JSON objects, I think I'd like to try that to just display all the information from the tests in the browser right now... But where would I write that? I have one Node.js file right now, which is running the tests and using JSON.stringify() to stick the JSON'd results into a file. Can I generate the HTML right after I create the JSON? (And the main question- how would I create HTML from a JSON file?)
I'm just starting out with Node and JSON, any tips are highly appreciated.
Yes, you can create HTML from a JSON file.
Here's a simple example done with jQuery, first creating an array of all of the elements, and then using .join("") to parse them. Once parse, they can simply be appended anywhere in the DOM:
var json_file = {
"one": "Hi there",
"two": "Another item",
"three": "Third item"
}
var items = [];
$.each(json_file, function(key, val) {
items.push("<li id='" + key + "'>" + val + "</li>");
});
$("<ul/>", {
"class": "json-list",
html: items.join("")
}).appendTo("body");
// Sample extension showcasing manipulation of inserted HTML
$(".json-list #two").css('color', 'red');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Obviously, the more complicated your JSON (and desired HTML structure), the more complicated the method of parsing the JSON is going to be.
A templating engine would make your job significantly easier,
and there and hunderds of these. Some of the more popular ones are:
EJS
jQuery.dForm
JQuote2
JSON Template
JTemplates
Mustache
PURE
Tempo
Hope this helps! :)

Node.js code in html file

It is possible to mix HTML with node.js commands?
I want to make my site like in PHP so:
<html>
<!-- Some HTML -->
<?php
echo "example";
?>
</html>
So, server makes all commands, which are included in HTML file and than returns pure HTML to show it in users browser. I need this, because I want to get data from MySQL database and then show it on my site.
In all tutorials I found only:
res.write("<Some html>");
And there is nothing about keeping html in separate files and add to them some server-side js.
Find a templating engine and build your application around that, because what you want is not possible.
For a list of compatible template engines, take a look here:
https://github.com/joyent/node/wiki/modules#wiki-templating
Your example using Express and EJS (which I use). Jade seems like overkill to me, but that's just my opinion.
// index.ejs (the html template)
<html>
<head></head>
<body>
<div><%= example %></div>
</body>
</html>
And in your node app:
app.get('/', function (req, res, next) {
res.render('index.ejs', {
layout: false,
locals: {
example: "Hello world!"
}
});
});
That's pretty much the basics of using EJS. I personally like it over Jade because the people I use to do up the html don't hand it to me in Jade format, and it's very similar to how I used to do php templating.
There is more you can do with the templates of course, you can put javascript in them to say, loop through an array returned by a database, include other .ejs files. You just need to dig into the docs and examples on the web.
Use the function res.write is enough.
You can generate some string with html syntax, like "<html>..</html>", then you put it into the res.write and you get response with a html file.
The point is how to generate the string with html syntax.
If we have a template file like this:
<html>
<body>
<h1>{{ "Hello" + " world!" }}</h1>
</body>
</html>
We want to get the "Hello world!" between <h1> and </h1>. So we can have the work done by:
read the template file with fs.readFile
use regular expression to get the content between {{ and }}
use eval to evaluate the content, and replace them.
After doing this, you can get the string with html syntax. and that is what most template engines(like ejs, jade) do, of course they have more complex works to do.
I hope that this can help you know more about template engine with node.js, and please forgive my poor English...
Have you tried a web application framework like express?
Check it out here!