syntax.us Let the syntax do the talking
Blog Contact Posts Questions Tags Hire Me

Question:
How do I highlight Python syntax inside an HTML code-element served by a Rails application?

Recently I encountered a use-case where I wanted to highlight Python syntax inside a blog post.

The website was being served by Rails.

I searched on google and found a JavaScript library named highlight.js:

https://highlightjs.org

I read the directions there and then added some syntax to my Rails layout file:
<!DOCTYPE html>
<html>
<head>
  <title>Syntax611.com</title>
  <link href="/myassets/site.css" media="all" rel="stylesheet" />
  <script src="/myassets/jquery-2.1.0.min.js"></script>
  <meta charset="utf-8" />

  <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/styles/default.min.css">
  <script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/highlight.min.js"></script>
  <script>hljs.initHighlightingOnLoad();</script>

</head>
<body>

<%= render 'layouts/app_body' %>

</body>
</html>

I then placed the Python syntax in a pre-code element:

<pre>
  <code class='python'>
class Mapping:
    def __init__(self, iterable):
        self.items_list = []
        self.__update(iterable)

    def update(self, iterable):
        for item in iterable:
            self.items_list.append(item)

    __update = update   # private copy of original update() method

class MappingSubclass(Mapping):

    def update(self, keys, values):
        # provides new signature for update()
        # but does not break __init__()
        for item in zip(keys, values):
            self.items_list.append(item)
  </code>
</pre>

And I looked at it with my browser.

In my browser, the Python syntax looks like this:
class Mapping:
    def __init__(self, iterable):
        self.items_list = []
        self.__update(iterable)

    def update(self, iterable):
        for item in iterable:
            self.items_list.append(item)

    __update = update   # private copy of original update() method

class MappingSubclass(Mapping):

    def update(self, keys, values):
        # provides new signature for update()
        # but does not break __init__()
        for item in zip(keys, values):
            self.items_list.append(item)
I am pleased with highlight.js and think it is a good general purpose syntax highlighting library.
syntax.us Let the syntax do the talking
Blog Contact Posts Questions Tags Hire Me