Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
458 views
in Technique[技术] by (71.8m points)

pretty print - How to format code in html / css / js/ php

I'm looking for a way to automatically format and color code I write in an HTML document. I know wikipedia does it, for example on the page: http://en.wikipedia.org/wiki/Nested_function

I'm sure there are libraries out there to do this, but I can't for the life of me, find one. Does anyone have any suggestions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Have a look at the Prettify JavaScript library. It's the one generally used by people (it's the one being used here on SO, for example.)

You would use it like this:

In your <head> element:

<link href="prettify.css" type="text/css" rel="stylesheet" />
<script type="text/javascript" src="prettify.js"></script>

In your <body> element:

<body onload="prettyPrint()">
  <!-- any HTML you like here... -->
  <pre class="prettyprint">
def say_hi():
    print("Hello World!")
  </pre>
  <!-- any HTML you like here... -->
</body>

That's for simple use of the library. If you're using other JavaScript on your page I would recommend other methods for enabling the Prettify library (i.e., don't use the onload attribute of the <body> element.) For example, if you're using jQuery, I wrote this jQuery plugin that I usually use to syntax highlight certain elements:

// Extend jQuery functionality to support prettify as a prettify() method.
jQuery.fn.prettify = function () { this.html(prettyPrintOne(this.html())); };

Used like this:

$('#my-code-element').prettify();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...