Reputation: 207
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.
Upvotes: 4
Views: 432
Reputation: 52829
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
Upvotes: 3
Reputation: 2082
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.
Upvotes: 1