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

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

Related

Get the full filename of the post in convecter of Jekyll

I am using markdown extension in jekyll using convecter. For example:
module Jekyll
class MyConverter < Converter
safe false
priority :high
def matches(ext)
ext =~ /^.(md|markdown)$/i
end
def output_ext(ext)
".html"
end
def my_process (content)
# something
end
def convert(content)
# Here my markdown processing
# content = my_process(content)
# Here I want to use the path to the markdown file
# puts (filename)
site = Jekyll::Site.new(#config)
converter = site.find_converter_instance(Jekyll::Converters::Markdown)
converter.convert(content)
end
end
end
Is it possible to get the full name of the file or its location for which markdown text is converted to html?
For example, I have a markdown file:
Bla bla bla.
[Text of the link](gallery)
Bla bla bla
And I want a list of the files in directory gallery. How to get a list of files from a specific directory I know, but in the convecter I need to know the full path to this markdown file. Is there any way to do that?
Use Jekyll::Hook:
module Jekyll
class MyHookProcess
class << self
def my_process(content)
# something
content
end
end
end
end
Jekyll::Hooks.register([:posts], :pre_render) do |post|
#puts ("post.date = " + post.date)
#puts ("post.path = " + post.path)
#puts ("post.url = " + post.url)
post.content = Jekyll::MyHookProcess.my_process(post.content)
end

Calling one jekyll plugin from another

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)

Trying to access a variable inside a block

I'm trying to make a simple rss generator. My initialize method works fine and the update method runs without an error too but the new item in the update method never get added to the rss feed. I think it has something to do with how i'm accessing the variable 'maker' but i'm not sure.
require "rss"
class RSS_Engine
def initialize
#rss = RSS::Maker.make("atom") do |maker|
maker.channel.author = "Jamie"
maker.channel.updated = Time.now.to_s
maker.channel.about = "http://www.ruby-lang.org/en/feeds/news.rss"
maker.channel.title = "Example Feed"
#maker = maker
end
end
def update
#maker.items.new_item do |item|
item.title = "Test"
item.updated = Time.now.to_s
end
end
def print_rss
puts #rss
end
end
rss = RSS_Engine.new
rss.update
rss.print_rss
I got the original code from this example:
rss = RSS::Maker.make("atom") do |maker|
maker.channel.author = "matz"
maker.channel.updated = Time.now.to_s
maker.channel.about = "http://www.ruby-lang.org/en/feeds/news.rss"
maker.channel.title = "Example Feed"
maker.items.new_item do |item|
item.link = "http://www.ruby-lang.org/en/news/2010/12/25/ruby-1-9-2-p136-is-released/"
item.title = "Ruby 1.9.2-p136 is released"
item.updated = Time.now.to_s
end
This code works fine but i want to be able to add new posts to the rss feed over time so i'm trying to put the 'new.item' bit into it's own method.
The problem is not #maker variable, you have to invoke to_feed method to regenerate the feed after you modify it out of the code block.
So you need to add #rss = #maker.to_feed at the end of your update method.
One more thing about creating a new feed entry, link or id attribute need to be set.
Below code will work for you:
def update
#maker.items.new_item do |item|
item.link = "http://test.com"
item.title = "Test"
item.updated = Time.now.to_s
end
#rss = #maker.to_feed
end
If you are interested about why, you can take a look ruby rss source code. And below code(under rss/maker/base.rb) is the root cause why you need to invoke to_feed method if you modify feed out of the block:
def make(*args, &block)
new(*args).make(&block)
end
def make
yield(self)
to_feed
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