0

I have the following data that my Python (Flask) application passes to a Jinja2 template and renders it as HTML:

--- a
+++ b
[
@@ -0 +0 @@
 {
  u'po': u'04312',
  u'storage': [
  @@ -2,1 +2,1 @@
  @@ -2,1 +2 @@
  +{u'type': u'FusionIO', u'capacity': 3000, u'number': 2, u'speed': u'N/A', u'total_capacity': 6000},
  ],
  u'serial': u'YYZ666',
  u'added_by': ObjectId('5208f7e054d79f70f9e13f7f'),
  u'edited_by': ObjectId('5208f7e054d79f70f9e13f7f'),
 -u'revision': 2,
 +u'revision': 3,
  u'status': u'Prod',
 -u'edited_date': datetime.datetime(2013, 8, 19, 21, 40, 30, 275000),
 +u'edited_date': datetime.datetime(2013, 8, 20, 13, 34, 25, 621000),
 -u'memory': u'256',
 +u'memory': u'1024',
  u'racked': u'Yes',
 @@  @@
 },
]

HTML source:

<div class="server-diff">
  <h2 class="dashboard-heading">Diff</h2>
  <p>--- a
+++ b
[
@@ -0 +0 @@
 {
  u&#39;po&#39;: u&#39;04312&#39;,
  u&#39;storage&#39;: [
  @@ -2,1 +2,1 @@
  @@ -2,1 +2 @@
  +{u&#39;type&#39;: u&#39;FusionIO&#39;, u&#39;capacity&#39;: 3000, u&#39;number&#39;: 2, u&#39;speed&#39;: u&#39;N/A&#39;, u&#39;total_capacity&#39;: 6000},
  ],
  u&#39;serial&#39;: u&#39;YYZ666&#39;,
  u&#39;added_by&#39;: ObjectId(&#39;5208f7e054d79f70f9e13f7f&#39;),
  u&#39;edited_by&#39;: ObjectId(&#39;5208f7e054d79f70f9e13f7f&#39;),
 -u&#39;revision&#39;: 2,
 +u&#39;revision&#39;: 3,
  u&#39;status&#39;: u&#39;Prod&#39;,
 -u&#39;edited_date&#39;: datetime.datetime(2013, 8, 19, 21, 40, 30, 275000),
 +u&#39;edited_date&#39;: datetime.datetime(2013, 8, 20, 13, 34, 25, 621000),
 -u&#39;memory&#39;: u&#39;256&#39;,
 +u&#39;memory&#39;: u&#39;1024&#39;,
  u&#39;racked&#39;: u&#39;Yes&#39;,
 @@  @@
 },
]</p>
</div>

I would like to be able to change the text colour of lines that start with + to green and - to red.

I know you can do regexps in javascript so I'm guessing you can do something like getting all the lines in p and then apply a CSS to them but I have no idea how to do that.

How can I do this in javascript (or jquery, which I already use)/css?

Thank you.

4

1 回答 1

3

Get the text from the paragraph, split the lines and check the first character and add a class :

$('.server-diff p').text(function(_,txt) {
    var lines = txt.split('\n');

    $.each(lines, function(i, line) {
        var start = line.charAt(0);
        if (start == '+') {
            lines[i] = '<span class="green">'+line+'</span>';
        } else if (start == '-') {
            lines[i] = '<span class="red">'+line+'</span>';
        }
    });
    return lines.join('\n');
});
于 2013-08-20T14:50:33.660 回答