I was looking for a way to highlight code in this blog. There appear to be a few ways to go about it. What I like most so far is Google's SyntaxHighlighter. Using nothing but CSS and Javascript, I can make code snippets look good.
For example
C#:
public class SomeClass : SomeBaseClass
{
public string FirstName {get; set;}
public string LastName {get; set;}
public SomeClass(string firstname, string lastname)
{
this.FirstName = firstname;
this.LastName = lastname;
}
public string GetFullName()
{
return String.Format("{0} {1}", this.FirstName, this.LastName);
}
}
Python:
class Spam:
def __init__(self):
self._state = []
def eggs(self, arg):
self._state += arg
end
Ruby:
class SomeRandomClass
def initialize(hash={})
#do some initialization with the hash
end
end
I think that this is pretty slick.
The other cool thing is that I can conditionally control when to include the css and js files. Say I have a collection of posts to display on this page. If none of the posts contains code, why include the additional files?
#The /posts action
get '/posts' do
@posts = Post.all
#not_empty? is a method I've added to Array/Hash
@requires_highlighting = @posts.select {|p| p.contains_code?}.not_empty?
erb :posts
end
An then in the layout.erb file, I just check for the presence of the @requires_highlighting variable. Simple, but effective
<% if @requires_highlighting %>
<%= render_syntax %>
<% end %>
No comments have been posted.