4

I use Jekyll and I need to add classes in a HTML tags after rendering Markdown to HTML.

I could use jQuery or simple JavaScript for this task but I would like to understand how hooks work with Jekyll.

I wrote this in a Gemfile:

Jekyll::Hooks.register :pages, :post_render do |post|
    # here I need write something with Ruby language
end

Only a few pages from a collection are affected by this: How can I do it?

I would like to add this:

class="line-numbers"

For all pre tags in the HTML rendered file.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
OVER-C
  • 69
  • 2
  • 5

2 Answers2

3

If you want to parse one collection's documents, you can do it with Nokogiri.

You can use a _plugins/hook_pre.rb like this :

Jekyll::Hooks.register :documents, :post_render do |document|
    require 'nokogiri'
    # as posts are also a collection, we can have a document from posts
    # or even from another collection
    #### SET YOUR COLLECTION NAME HERE ####
    isSearchable = document.collection.label == 'mycollection'

    if isSearchable == true
        doc = Nokogiri::HTML(document.output)
        pre = doc.css("pre").add_class('line-numbers')
        document.output = doc.to_html
    end
end
David Jacquel
  • 51,670
  • 6
  • 121
  • 147
  • It's work very well, thank you. More one thing, if I want a variable in a front matter (yaml) with options like -> pre-render: ['line-number', 'other-stuff'] and use this for add a class in pre tag in a HTML file. Can you help please ? – OVER-C Mar 15 '16 at 12:25
  • `pre-render` front matter variable can be accessed with `document.data['pre-render']` in your plugin. – David Jacquel Mar 15 '16 at 13:07
1

Here is the answer: Add ID or Class to Markdown-element

You add a class like this:

{:.line-numbers}
{% highlight ruby %}
def print_hi(name)
  puts "Hi, #{name}"
end

Which would add class line-numbers to the <figure> tag, which wraps <pre>, hope that helps.

Community
  • 1
  • 1
Max Filippov
  • 2,024
  • 18
  • 37
  • This is it. I start from a Markdown document, so I can not use the Liquid language (technically yes, but not on this case). I would like use the Ruby language instead. Thanks. – OVER-C Mar 14 '16 at 14:12