Calling one jekyll plugin from another - ruby

I'm writing a jekyll plugin to create a custom tag. It takes an argument and spits out a string of HTML. I've got it mostly working - I can pass it arguments and get back HTML based on those arguments. Great.
Here's what has me stumped: I want to include the render of another plugin as part of my own.
My aspirational plugin is jekyll_icon_list, the plugin I want to use is jekyll-inline-svg. Here's the (abbreviated) code:
require 'jekyll_icon_list/version'
require 'jekyll'
require 'jekyll-inline-svg'
module JekyllIconList
class IconList < Liquid::Tag
def initialize(tag_name, raw_args, tokens)
#raw_args = raw_args
#tokens = tokens
super
end
def parse_arguments(raw_args, settings)
# (Unrelated stuff)
end
def generate_image(icon, settings, context)
# (Unrelated stuff)
# Problem Here:
Liquid::Tag.parse(
'svg',
icon,
#tokens,
Liquid::ParseContext.new
).render(context)
end
def render(context)
# Builds my HTML, using generate_image in the process
end
end
end
Liquid::Template.register_tag('iconlist', JekyllIconList::IconList)
This doesn't throw any errors, but it also doesn't return anything at all.
Other things I've tried:
Jekyll::Tags::JekylInlineSvg.new(
returns a private method error. Jekyll doesn't want me making my own tags directly.
'{% svg #{icon} %}'
Returns exactly that literally with the icon substituted in; jekyll clearly doesn't parse the same file twice.
I'm trying to figure it out from Jekyll's source, but I'm not so practiced at reading source code and keep hitting dead ends. Can anyone point me in the right direction? Much appreciated.

Answering my own question:
def build_svg(icon_filename)
tag = "{% svg #{icon_filename} %}"
liquid_parse(tag)
end
def liquid_parse(input)
Liquid::Template.parse(input).render(#context)
end
Basically create a tiny template consisting of the tag you want to call, and hand it off to Liquid for parsing.
Below is the dirty way, which I used before I found the proper way:
Jekyll::Tags::JekyllInlineSvg.send(:new, 'svg', icon_filename, #tokens).render(context)

I found this question and answer, and while it's correct, I wanted to provide a full end-to-end example.
I wanted to wrap Jekyll Scholar's {% cite %} tags in my own content:
module Jekyll
class RenderTimeTag < Liquid::Tag
def initialize(tag_name, text, tokens)
super
#text = text
end
def build_cite(content, context)
tag = "{% cite #{content} %}"
return liquid_parse(tag, context)
end
def liquid_parse(input, context)
template = Liquid::Template.parse(input)
template.render(context)
end
def render(context)
citation = build_cite(#text, context)
# Yeah, I know this is bad HTML:
"<span tabindex=\"0\" class=\"citeblock\">#{citation}</span>"
end
end
end
Liquid::Template.register_tag('pretty_cite', Jekyll::RenderTimeTag)

Related

Using Liquid custom tags to output multiple `span` elements`

I'm playing with Jekyll plugins and their ability to create custom tags and I've run into an issue extending my tag to accept a comma separated list.
I started with the following:
{% symbol R %}
And the matching plugin code:
module Jekyll
class Symbol < Liquid::Tag
def initialize(tag_name, text, tokens)
super
#text = text
end
def render(context)
"<span class='symbol-#{#text}'>#{#text}</span>"
end
end
end
Liquid::Template.register_tag('symbol', Jekyll::Symbol)
And the output on my page, as expected, is:
<span class="symbol-R">R</span>
What I'm trying to do now is amend this plugin so I can pass in a comma separated list, for example:
{% symbol R,G %}
I updated my plugin code to this:
module Jekyll
class Symbol < Liquid::Tag
def initialize(tag_name, text, tokens)
super
#text = text
end
def render(context)
symbol = #text.split(',').map(&:strip)
symbol.each do |item|
puts item # to test in terminal
"<span class='symbol-#{#text}'>#{#text}</span>"
end
end
end
end
Liquid::Template.register_tag('symbol', Jekyll::Symbol)
Terminal outputs correctly:
R
G
And my expectation was that I'd get the following on my page:
<span class="symbol-R">R</span><span class="symbol-G">G</span>
But all that shows up on the page is:
RG
Could I get some help in figuring this out? I feel like I'm super close... it's just the actual page rendering I'm clearly messing up on.
In Ruby your function will return the last expression that it executed. For you, this is the symbol.each do … end.
each returns various things, but what it does not do by itself is return the contents of its block. For that, you want map:
symbol.map do |item|
puts item # to test in terminal
"<span class='symbol-#{#text}'>#{#text}</span>"
end
Replace
symbol.each do |item|
puts item # to test in terminal
"<span class='symbol-#{#text}'>#{#text}</span>"
end
by
output = ""
symbol.each do |item|
output =+ "<span class='symbol-#{item}'>#{item}</span>"
end
output

Preprocessing markup files in jekyll

I would like to write a preprocessor that operates on a range of markup languages before they're processed into HTML by Jekyll. Ideally the user would simply create a file called _posts/xxyyzz.md.wmd, and Jekyll would preprocess it into xxyyzz.md using a plugin I provide, and then process that into HTML in the usual way.
It looks like Jekyll's Converter framework doesn't allow that, because the output_ext function is only given the final extension "wmd", preventing it from returning ".md" for ".md.wmd", ".textile" for ".textile.wmd", etc.
Is there a way to implement a chain of processing steps like this?
EDIT: grammar
Maybe you can try to use a Generator plugin that uses your wmd converter:
require "yourWmdConverter"
module Jekyll
class ConvertWmd < Jekyll::Generator
def initialize(config)
config['convert_wmd'] ||= true
end
def generate(site)
#site = site
site.posts.docs.each { |post| convertWmd post }
end
private
def convertWmd(post)
post.content = yourWmdConverter post.content
end
end
end

Two versions of each blog post in Jekyll

I need two versions of each of my posts in a very simple Jekyll setup: The public facing version and a barebones version with branding specifically for embedding.
I have one layout for each type:
post.html
post_embed.html
I could accomplish this just fine by making duplicates of each post file with different layouts in the front matter, but that's obviously a terrible way to do it. There must be a simpler solution, either at the level of the command line or in the front matter?
Update:
This SO question covers creating JSON files for each post. I really just need a generator to loop through each post, alter one value in the YAML front matter (embed_page=True) and feed it back to the same template. So each post is rendered twice, once with embed_page true and one with it false. Still don't have a full grasp of generators.
Here's my Jekyll plugin to accomplish this. It's probably absurdly inefficient, but I've been writing in Ruby for all of two days.
module Jekyll
# override write and destination functions to taking optional argument for pagename
class Post
def destination(dest, pagename)
# The url needs to be unescaped in order to preserve the correct filename
path = File.join(dest, CGI.unescape(self.url))
path = File.join(path, pagename) if template[/\.html$/].nil?
path
end
def write(dest, pagename="index.html")
path = destination(dest, pagename)
puts path
FileUtils.mkdir_p(File.dirname(path))
File.open(path, 'w') do |f|
f.write(self.output)
end
end
end
# the cleanup function was erasing our work
class Site
def cleanup
end
end
class EmbedPostGenerator < Generator
safe true
priority :low
def generate(site)
site.posts.each do |post|
if post.data["embeddable"]
post.data["is_embed"] = true
post.render(site.layouts, site.site_payload)
post.write(site.dest, "embed.html")
post.data["is_embed"] = false
end
end
end
end
end

Can't get page data from Jekyll plugin

I'm trying to write a custom tag plugin for Jekyll that will output a hierarchical navigation tree of all the pages (not posts) on the site. I'm basically wanting a bunch nested <ul>'s with links (with the page title as the link text) to the pages with the current page noted by a certain CSS class.
I'm very inexperienced with ruby. I'm a PHP guy.
I figured I'd start just by trying to iterate through all the pages and output a one-dimensional list just to make sure I could at least do that. Here's what I have so far:
module Jekyll
class NavTree < Liquid::Tag
def initialize(tag_name, text, tokens)
super
end
def render(context)
site = context.registers[:site]
output = '<ul>'
site.pages.each do |page|
output += '<li>'+page.title+'</li>'
end
output += '<ul>'
output
end
end
end
Liquid::Template.register_tag('nav_tree', Jekyll::NavTree)
And I'm inserting it into my liquid template via {% nav_tree %}.
The problem is that the page variable in the code above doesn't have all the data that you'd expect. page.title is undefined and page.url is just the basename with a forward slash in front of it (e.g. for /a/b/c.html, it's just giving me /c.html).
What am I doing wrong?
Side note: I already tried doing this with pure Liquid markup, and I eventually gave up. I can easily iterate through site.pages just fine with Liquid, but I couldn't figure out a way to appropriately nest the lists.
Try:
module Jekyll
# Add accessor for directory
class Page
attr_reader :dir
end
class NavTree < Liquid::Tag
def initialize(tag_name, text, tokens)
super
end
def render(context)
site = context.registers[:site]
output = '<ul>'
site.pages.each do |page|
output += '<li>'+(page.data['title'] || page.url) +'</li>'
end
output += '<ul>'
output
end
end
end
Liquid::Template.register_tag('nav_tree', Jekyll::NavTree)
page.title is not always defined (example: atom.xml). You have to check if it is defined. Then you can take page.name or not process the entry...
def render(context)
site = context.registers[:site]
output = '<ul>'
site.pages.each do |page|
unless page.data['title'].nil?
t = page.data['title']
else
t = page.name
end
output += "<li>'+t+'</li>"
end
output += '<ul>'
output
end
Recently I faced a similar problem where the error "cannot convert nill into string" is just blowing my head. My config.yml file holds a line something like this " baseurl: /paradocs/jekyll/out/ " now thats for my local for a server i need to make that beseurl empty and the error starts to appear in build time so finally i have to made " baseurl: / " .. And that's did my job.

Liquid error: wrong number of arguments

I am trying a simple Jekyll plugin:
class MonthlyArchives < Liquid::Tag
def initialize(tag_name, text, tokens)
super
#text = text
end
def render(context)
"#{#text} #{Time.now}"
end
end
Liquid::Template.register_tag('monthly_archives1', Jekyll::MonthlyArchives)
When I try to run it in page as follows:
{% monthly_archives1 %}
I get Liquid error: wrong number of arguments (2 for 0). Any ideas ?
I haven't had any chance to build something with Liquid, but the Jekyll wiki page about building your own plugins has the whole class surrounded with module before registering that
module Jekyll
...your code...
end
Liquid::Template.register_tag('monthly_archives1', Jekyll::MonthlyArchives)
that might be an issue.

Resources