I'm trying to display a JSON object nicely (this means on several lines with indentation) with Alex Gorbatchev plugin : http://alexgorbatchev.com/SyntaxHighlighter/
Unfortunately, it all displays on a single line.
I'm using the javascript brush.
I've created a code pen : http://codepen.io/hugsbrugs/pen/XJVjjP?editors=101
var json_object = {"hello":{"my_friend":"gérard", "my_dog":"billy"}};
$('#nice-json').html('<pre class="brush: javascript">' + JSON.stringify(json_object) + '</pre>');
SyntaxHighlighter.highlight();
Please don't give a list of other plugins since I know there is a bunch but I don't want to load additional plugins ... I'd like to achieve it with this plugin.
Thanks for your help
Try indenting the json with the stringify method.
JSON.stringify(json_object, undefined, 2);
You can use the optional third parameter of JSON.stringify(...) which is the space argument.
Change:
JSON.stringify(json_object)
to:
JSON.stringify(json_object, null, '\t')
Here is your codepen updated to show the result of the above modifications. The above modification causes your JSON to be pretty printed over multiple lines.
Related
I'm new to angular, and I would like to know if there's is a way to send a string to the Html file with a variable inside?
test.ts
test: string = "Display this {{testText}}";
testText: string = "Success";
test.html
<p>{{test}}</p>
What I want to achieve is that it displays this: Display this Success.
I'm just curious if this is possible, perhaps I can retrieve from an API chunks of HTML string and display them like that.
**
It is basic Javascript string operation. For this, there is nothing special with Angular at your TypeScript file.
Without handling updates on test
On Typescript file you have two options to merge strings:
First Way:
testText: string = "Success";
test: string = `Display this ${this.testText}`;
Second Way:
testText: string = "Success";
test: string = "Display this " + this.testText;
Of course you can see a problem with both of them. What will happen when you update your test? Based on these ways, the testText just initializing when the component instance is created, so if you want to fetch changes on your test variable you should use the way from one of following
**
First Way:
test.html
<p>Display is {{testText}}</p>
<p>{{'Display is ' + testText}}
Socond Way:
Specifically you can create a custom Pipe. You should check documentation about how are them work. For only this case you don't need to use this way. Pipes are generally for more generic or more complex operations.
Third way:
(more bad than others. Because change detector of Angular will not understand when your content should update the paragraph. You should use others.)
test.ts
getTestText() { return 'Display is ' + this.testText }
test.html
<p>{{ getTestText() }}</p>
**
Binding Dynamic Html Content
For binding any dynamic HTML template you need to use innerHTML attribute like
<div [innerHTML]="htmlVariable"></div>
but this is not a trusted way because there is nothing to check is the html is trusted or is it valid etc. Or if the html contains the selector of any component, it won 't render as expected. You should use more complex ways to do it.
I have a generic template in play 2.6, that I want to pass in a variable amount of HtmlContents. I've defined the template like this (including the implicit parameter I have in case that changes anything):
#(foo: String)(content: Html*)(implicit bar: Bar)
On the template side, this works fine-- I can dissect content with for and render it as I want. However, I haven't been able to figure out a clean way to invoke the variable arguments from the underlying template.
e.g, I have a view named "Baz":
#(something: String)(implicit bar: Bar)
In it, I try to invoke the template with multiple Html arguments. I've tried the following:
#template("fooString"){{123},{abc}}
and
#template("fooString")({123}, {abc})
and
#template("fooString"){{123}, {abc}})
And various other permutations, but inside of an enclosing bracket it seems to interpret everything literally as a single parameter in the HtmlContent vararg.
However, this ended up working as I intended, passing in multiple HtmlContents:
#template("fooString")(Html("123"), Html("abc"))
So that works, and I can use a triple-quoted interpolated string for a large Html block-- but it seems like there should be a cleaner way to do this, and the string interpolation is dangerous as it doesn't do html escaping.
Is there a way to do this using the { enclosed syntax? I'd like to understand more what is actually happening on an underlying level, and how play parses and generates HtmlContent in brackets.
So consider you have below template
// main.scala.html
#(title: String)(contents: Html*)
There are different ways you can call this template
Option #1
This is what you already posted in the question
#main("This is a title")(Html("abc"), Html("123"))
Options #2
#html1 = {
Hello
}
#html2 = {
<div>Tarun</div>
}
#main("This is a title")(html1, html2)
Option #3
#main("This is a title")(Html(<div>Tarun
</div>.toString), Html(<div>
Lalwani
</div>.toString))
Options #4
This is not exactly same option, but needs change in Template signature itself
#(title: String)(contents: List[String])
And then calling it like below
#main("This is a title")(List(
"""<div>
Tarun
</div>
""", """Hello"""))
Option #5
This requires code files and was already answered on another SO thread
Paul Draper's answer on Why doesn't this pass multiple HTML parameters to template
I'm using Jquery to get a list of elements having a class "x".
html:
<p class="x">Some content</p>
<p class="x">Some content#2</p>
If we use Jquery to get both these html elements and do something with it- we use something like:
$(".x").text("changed text");
This will change the text of both the paragraphs. From $(".x") - How can we add a array - subscript notation like we can do with getElementsByclassName as follows:
document.getElementsByClassName("x")[0].innerHTML
I tried this
$(".x")[0].text("asasa")- it doesn't work gives a typeerror in javascript console. I also tried get API here -http://jsfiddle.net/probosckie/jnz825mp/ - and it doesnt work
the error is Uncaught TypeError: $(...).get(...).text is not a function
None of the solutions below WORK!
You can use the get() method for accessing an element from the array, for example:
$(".x").get(index).textContent = "changed text";
More info: https://api.jquery.com/jquery.get/
And for obtaining HTML (innerHTML) you call the .html() function:
// This is equal to document.getElementsByClassName("x")[0].innerHTML
$(".x").get(0).innerHTML;
If you want to set the HTML, then just provide your HTML code inside the function call like this .html('<h1>Hello, World!</h1>').
EDIT: .get() returns the DOM object not the jQuery wrapped element. Therefore .text() and .html() doesn't work. Unless you wrap it.
More options:
$(".x").get(0).innerHTML;
$($(".x").get(0)).html();
$(".x:first").html();
You can do it like this way:
$('.x:eq(0)').text('changed text');
or:
$('.x').eq(1).text('bbb');
both works well
sorry for my before answer..
The solution $(".x").get(index)... will first match all .x (which is bad performance). And then it will filter
If you have 1000 .x it will fill an 1000 items in the jQuery object (before filtered)
But
$(".x:first").text("changed text"); will do better because it won't yield all .x and then filter , but will do it at a first single step (without filling 1000 items)
I am trying to read a cookie value inside the play framework template (not inside a controller). I am trying the following which is not working:
# val cookieVal = request.cookies.get('PLAY_SESSION').value
Any suggestions to fix this will be greatly appreciated. The reason why I am trying this is to change how the page gets rendered based on a cookie value.
In templates you define vals as follows:
#defining(request.cookies.get('PLAY_SESSION').value) { theValue =>
<div>Hello #theValue</div>
}
I personally prefer to read the cookies in the controller and pass them to the template if needed.
suppose PLAY_SESSION stored "37f0983881ba00636868b42234a360d466fb944c-block_status=0&userId=159313257462171"
and you have to render on the basis of the value of block_status.
then in this case you can get its value by
session.get("block_status").get
to use it in template you have to import#implicit session:play.api.mvc.Session at your template.
now you can easily get values at template by #session.get("block_status").get
request.cookies.get("Org").get.value
I'm very new at AJAX and Javascript and need a bit of help with this code.
Here is the bit of JSON I'm using
{"URL":"www.youtube.com","Total URLs":132,"Completed":63}
I need to get each one of these values and display in different HTML input text boxes using AJAX.
Current URL: <input type="text" name="urlqueue">
Total URLs: <input type="text" name="total">
Completed: <input type="text" name="completed">
Right now I have
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.form.total.value = ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "test_results.php", true);
ajaxRequest.send(null);
You can see this doesn't work anymore. I use to have the file containing only 1 number and no JSON. Now I need to use the file for many results with JSON and need some direction.
How do I display the JSON in the HTML input boxes using AJAX?
Parse the JSON, either by using a JSON parsing library or by using eval. Note that using eval can be very dangerous, as you can introduce cross-site scripting vulnerabilities if it is used incorrectly.
The resulting object will have the values, so you can set each field individually by, for example:
document.form.total.value = jsonObject["Total URLs"];
Note that when you make an AJAX and retrieve the response, the response text is not JavaScript object. It's just string so you should evaluate the string to JavaScript Object. The following code will produce that in a quick way. But Douglas Crockford who is the master of JavaScript says that "eval is evil".
var data = eval('(' + ajaxRequest.responseText + ')');
document.form.total.value = data[Total URLs]
also I want to remember that avoid spaces in property names. For example, you should have a property named "Total_URLs" or "TotalURLs" etc. instead of "Total URLs"