Scott Scott - 1 year ago 54
Javascript Question

Why aren't there line breaks in this <pre> tag?

I'm using highlight.js to display some JSON I'm receiving from a subscription. It is coloring the text but it is not adding line breaks as expected (via their demos). Also, a couple places in the documentation give the impression that the library generates new lines. See the

option here.

Here is my current code (I've tried a few different things):

channel : 'TEST',
message : function(m){
var hlt = hljs.highlight('json',m);
$('#jsonOutput').html("<pre>" + hlt.value + "</pre>");

And here is what the DOM looks like:

enter image description here

But here is the output:

enter image description here

How can I get line breaks? I want it to look similar to this:



Answer Source

You don't have any line-breaks in your code. The highlight function will only apply the formatting options, when the json-string was formatted. You string is only one single line. So, you will have to bring it in the right format first and then you can highlight it:

function print_r(object,html){
    if(html) return '<pre>' +  JSON.stringify(object, null, 4) + '</pre>';
    else return JSON.stringify(object, null, 4);

var m = {"id":"TESTWIDGET1","value":351,"timestamp":"2016-08-31T12:03:24.3403952-05:00"};
var hlt = hljs.highlight('json',print_r(m));

Please be aware that I changed the var m from string to object (just remove the sourrunding ').

A working fiddle:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download