I have made my onw jekyll plugin which gives some text special css (spoiler hider).
This is my code:
class Spoiler < Liquid::Tag
def initialize(tag_name, input, tokens)
super
#input = input
end
def render(context)
output = "<div class='spoiler'>" + #input + "<div>"
return output;
end
end
Liquid::Template.register_tag('spoiler', Spoiler)
There is example how I want to use it in my markdown posts:
---
layout: post
title: "testing file"
date: 2019-09-25
category: article
---
aaaaaaaaaaa {% spoiler secret text %} bbbbbbbbbbbb
but this is how page looks like:
When I look in to generated source code, the text looks like this:
<p>aaaaaaa <div class='spoiler'>secret text </div> bbbbbbbb</p>
What should I do make jekyll plugin generate html element instead of text ?
PS: If I manually replace < by < and > by >, it works fine.
Technically, every line separated by whitespace get rendered into an HTML <p> element.
To avoid generating <p> tags automatically, explicitly wrap lines in a <div>:
<div>
aaaaaaaaaaa {% spoiler secret text %} bbbbbbbbbbbb
</div>
Related
I created a Jekyll tag plugin, which works fine on all template (index/about/contact/default/page) except _layout/post.html. I have tried looking for a solution on Stackoverflow and Google, but I haven't found one yet.
I created a new "products" collection within which my custom Liquid-tag plugin called to render a block of HTML code on post.html. Here's the plugin,
module Jekyll
class AmazonAffiateHelper < Liquid::Tag
def initialize(tag_name, input, tokens)
super
#input = input
end
def render(context)
input_split = split_params(#input)
output = ""
if (input_split.length > 0)
href = input_split[0].strip
src = input_split[1].strip
src2 = input_split[2].strip
href2 = input_split[3].strip
output = "<a href=\"#{href}\" target=\"_blank\"><img border=\"0\" src=\"#{src}\""
output += " width=\"150\" class=\"center-block amazon-fix \"></a>"
output += " <img src=\"#{src2}\" width=\"1\" height=\"1\" border=\"0\""
output += " alt=\"\" style=\"border:none !important; margin:0px !important;\"/>"
output += " <br><br><a href=\"#{href2}\" class=\"btn btn-amazon amazon-fix\">"
output += "BUY ON AMAZON</a>"
end
return output
end
def split_params(params)
return params.split("|")
end
end
end
Liquid::Template.register_tag('amazon', Jekyll::AmazonAffiateHelper)
Resulting output for example is something like this,
Here's is a book you might like, {% amazon variable|variable2|variable3|variable4 %}
And I am not getting anything useful from bundler exec jekyll server --trace
What am I missing? Thanks in advance
PS: I am not a coder, but I am learning.
I have managed to work around it by creating a new jekyll-block plugin. Not sure why I need to do it this in the first place, but it works, and the solution is below - I am sure there must be a better way of doing it.
module Jekyll
class RecommendationBlock < Liquid::Block
def initialize(tag_name, markup, tokens)
super
#input = markup
end
def render(context)
contents = super
# very important for this solution
content = Liquid::Template.parse(contents).render context
output = content
return output
end
end
end
Liquid::Template.register_tag("recommendation", Jekyll::RecommendationBlock)
And then, on the post.html, I loop through products collection
{% for product in site.products limit 5}
# product.content has the custom amazon tag {% amazon variable1|variable2...%}, which is cause the problem
{% recommendation recom }{{ product }}{% endrecommendation %}
{% endfor}
I hope it helps someone if they run into the same problem.
Thanks everyone.
Problem:
Rendering QR codes for users in a Jekyll template keep the last QR for all users:
I have this code:
index.html
{% for person in staff %}
{% qr person.qr %}
{% endfor %}
qr.rb
require 'rqrcode_png'
class QrCodeTag < Liquid::Tag
def initialize(tag_name, url, tokens)
super
#url = url.strip
end
def lookup(context, name)
lookup = context
name.split(".").each { |value| lookup = lookup[value] }
lookup
end
def render(context)
page_url = "#{lookup(context, 'site.url')}#{lookup(context, #url)}"
qr = RQRCode::QRCode.new(page_url, size: 10) # Size increased because URLs can be long
png = qr.to_img
<<-MARKUP.strip
<div class="qrcode">
<img src="#{png.to_data_url}" alt="#{page_url}">
</div>
MARKUP
end
end
Liquid::Template.register_tag('qr', QrCodeTag)
2017-09-01-john-doe.md
---
category: staff
name: John Doe
qr: "http://www.johndoe.com/"
---
John is really cool...
2017-09-02-maria-doe.md
---
category: staff
name: John Doe
qr: "http://www.mariadoe.com/"
---
Maria is really cool..
Now, when rendering the page it renders the
page successfully but keeping the same object (With the QR code)
for all users rendered on the same page (They must be on the same page).
I'm quite sure that the problem is that in some how I'm not deleting the old object when creating the new one or something related to a global variable not assigned correctly.
In this case, each user should have a different QR code but they have all the same.
Workaround:
If you add the tag in the excerpt you will have the qr code tag rendered fine.
Now is there anyone can explain why if you add the data in the excerpt like the below example it will render a different QR code for each user, but if this is added as a variable in the front matter will be the same for all (Will have the last one repeated for all)?
---
category: staff
name: John Doe
qr: "http://www.johndoe.com/"
---
{% qr http://www.johndoe.com %}
John is really cool...
{% qr person.qr %} is passing the string "person.qr", not the corresponding value.
You can do {% qr {{p.qr}} %}.
This is the actual fix:
require 'rqrcode_png'
class QrCodeTag < Liquid::Tag
include Jekyll::LiquidExtensions
def initialize(tag_name, url, tokens)
super
params = Shellwords.shellwords url
#url = url.strip
end
def render(context)
page_url = Liquid::Template.parse('{{'+#url+'}}').render context
qr = RQRCode::QRCode.new(page_url, size: 4) # Size increased because URLs can be long
png = qr.to_img
png = png.resize(120, 120)
<<-MARKUP.strip
<div class="qrcode">
<img src="#{png.to_data_url}" alt="#{page_url}">
</div>
MARKUP
end
end
Liquid::Template.register_tag('qr', QrCodeTag)
So, we parse the string and get the real value for the variable.
Is it possible to include a html file from another domain inside a Jekyll template? And if so what would the syntax be?
I'm not a Ruby or Jekyll developer, more or less asking on behalf of another so please forgive me if the answer is obvious! At least I couldn't quite find the answer with some initial research.
In essence we're trying to pull the markup of a footer from another domain, this is how production will work so we're actually just trying to simulate it in our template deliverables.
Cheers
You cannot do this within the template itself. However, you could define a custom Liquid tag that scrapes the markup of the remote page, and then put that tag into template. This would be in a file called e.g. plugins/remote_footer.rb
require 'nokogiri'
require 'open-uri'
require 'uri'
module Jekyll
class RemoteFooterTag < Liquid::Tag
def initialize(tag_name, markup, tokens)
#markup is what is defined in the tag. Lets make it a URL so devs
#don't have to update code if the URL changes.
url = markup
#check if the URL is valid
if url =~ URI::regexp
#grab the remote document with nokogiri
doc = Nokogiri::HTML(open(url))
#search the document for the HTML element you want
#node = doc.at_xpath("//div[#id='footer']")
else
raise 'Invalid URL passed to RemoteFooterTag'
end
super
end
def render(context)
output = super
if #node
node.to_s
else
"Something went wrong in RemoteFooterTag"
end
end
end
end
Liquid::Template.register_tag('remote_footer', Jekyll::RemoteFooterTag)
And then in your template:
{% remote_footer http://google.com %}
I threw this together quickly and didn't check if it runs, but hopefully it's enough to work with. Keep in mind that this will run once when the liquid parser runs on the page, and if the remote element changes that will not be reflected until the Jekyll site is rebuilt.
I just stumbled into this problem and I couldn't find any working solution addressing all the use cases I had so I wrote my own plugin.
N.B. This is the first piece of ruby I ever wrote.
require 'nokogiri'
require 'open-uri'
require 'uri'
class Jekyll::IncludeRemoteTag < Jekyll::Tags::IncludeTag
##remote_cache = {}
def initialize(tag_name, markup, tokens)
super
#url = #file
end
def validate_url(url)
if url !~ URI::regexp
raise ArgumentError.new <<-eos
Invalid syntax for include_remote tag. URL contains invalid characters or sequences:
#{url}
Valid syntax:
#{syntax_example}
eos
end
end
def syntax_example
"{% #{#tag_name} http://domain.ltd css=\".menu\" xpath=\"//div[#class='.menu']\" param=\"value\" param2=\"value\" %}"
end
def render(context)
#url = render_variable(context) || #url
validate_url(#url)
if #params
validate_params
#params = parse_params(context)
end
xpath = #params['xpath']
css = #params['css']
if ! html = ##remote_cache["#{#url}_#{xpath}"]
# fetch remote file
page = Nokogiri::HTML(open(#url))
# parse extract xpath/css fragments if necessary
node = page.at_xpath(xpath) if xpath
node = page.css(css) if css
node = page if !node
raise IOError.new "Error while parsing remote file '#{#url}': '#{xpath||css}' not found" if !node
# cache result
html = ##remote_cache["#{#url}_#{xpath}"] = node.to_s
end
begin
partial = Liquid::Template.parse(html)
context.stack do
context['include'] = #params
partial.render!(context)
end
rescue => e
raise Jekyll::Tags::IncludeTagError.new e.message, #url
end
end
end
Liquid::Template.register_tag('include_remote', Jekyll::IncludeRemoteTag)
And you'd use it like this:
<!-- fetch header.html -->
{% assign url = 'http://mything.me/_includes/header.html' %}
{% include_remote {{ url }} %}
<!-- fetch menu.html and extract div.menu -->
{% include_remote 'http://mything.me/_includes/menu.html' css="div.menu" links=site.data.menu %}
<!-- fetch menu.html and extract div.menu (xpath version) -->
{% include_remote 'http://mything.me/_includes/menu.html' xpath="div[#class='menu']" links=site.data.menu %}
It basically works exactly like a normal include file but it's remote.
Available for download here: https://gist.github.com/kilianc/a6d87879735d4a68b34f
License MIT.
You can include Liquid tag plugin for Jekyll, it worked for me.
Add this in your site's Gemfile:
group :jekyll_plugins do
gem 'jekyll-remote-include', :github => 'netrics/jekyll-remote-include'
end
Use the tag in your posts as follows:
{% remote_include https://raw.githubusercontent.com/jekyll/jekyll/master/README.markdown %}
Or
{% capture products %}
{% remote_include http://localhost:8888/products.json %}
{% endcapture %}
...
{{ products }}
I am trying to find CSS elements in a page, containing white space at the end of the class name:
#agent = Mechanize.new
page = #agent.get(somepage)
Where the tag is:
<div class="Example ">
When trying:
page.search('.Example')
the element is not found and when trying:
page.search('.Example ') <- space following the name
Nokogiri raises an exception:
Nokogiri::CSS::SyntaxError: unexpected '$' after 'DESCENDANT_SELECTOR'
Your implied premise, that a class cannot be found because it contains a space, is incorrect. Class names do not include spaces. Proof:
require 'nokogiri'
html = <<End
<html>
<span class="Example ">One</span>
<span class="Example foo">Two</span>
</html>
End
doc = Nokogiri::HTML(html)
puts doc.search('.Example')
Output:
<span class="Example ">One</span>
<span class="Example foo">Two</span>
So I think your HTML document simply doesn't have a class containing Example in it. If you provided the sample HTML, this question would have been easier to answer.
To find all elements having class attribute ending in whitespace:
page.search('*').select{|e| e[:class] =~ /\s$/}
If you specifically target the class attribute you can include spaces. In my case the class value had a space:
<p class="Event_CategoryTree category">
Here is how I targeted that element using Nokogiri:
page.at_css("[class='Event_CategoryTree category']")
You can use Xpath instead.
The following code will return all div containers with the class a class with spaces :
doc = Nokogiri::HTML(page)
result = doc.xpath('//div[#class="a class with spaces"]')
Is it possible to nest custom Liquid tags written in ruby if one class has multiple optional tokens passed in as parameters? This question is rather hard for me to describe without providing the relevant example. Please excuse me if this question appears to be too specific a use case.
Given the following ruby code, sourced from Octopress (a jekyll fork), which creates a custom Liquid tag to parse tags.
# Title: Simple Image tag for Jekyll
# Authors: Brandon Mathis http://brandonmathis.com
# Felix Schäfer, Frederic Hemberger
# Description: Easily output images with optional class names, width, height, title and alt attributes
#
# Syntax {% img [class name(s)] [http[s]:/]/path/to/image [width [height]] [title text | "title text" ["alt text"]] %}
#
# Examples:
# {% img /images/ninja.png Ninja Attack! %}
# {% img left half http://site.com/images/ninja.png Ninja Attack! %}
# {% img left half http://site.com/images/ninja.png 150 150 "Ninja Attack!" "Ninja in attack posture" %}
#
# Output:
# <img src="/images/ninja.png">
# <img class="left half" src="http://site.com/images/ninja.png" title="Ninja Attack!" alt="Ninja Attack!">
# <img class="left half" src="http://site.com/images/ninja.png" width="150" height="150" title="Ninja Attack!" alt="Ninja in attack posture">
#
module Jekyll
class ImageTag < Liquid::Tag
#img = nil
def initialize(tag_name, markup, tokens)
attributes = ['class', 'src', 'width', 'height', 'title']
if markup =~ /(?<class>\S.*\s+)?(?<src>(?:https?:\/\/|\/|\S+\/)\S+)(?:\s+(?<width>\d+))?(?:\s+(?<height>\d+))?(?<title>\s+.+)?/i
#img = attributes.reduce({}) { |img, attr| img[attr] = $~[attr].strip if $~[attr]; img }
if /(?:"|')(?<title>[^"']+)?(?:"|')\s+(?:"|')(?<alt>[^"']+)?(?:"|')/ =~ #img['title']
#img['title'] = title
#img['alt'] = alt
else
#img['alt'] = #img['title'].gsub!(/"/, '"') if #img['title']
end
#img['class'].gsub!(/"/, '') if #img['class']
end
super
end
def render(context)
if #img
"<img #{#img.collect {|k,v| "#{k}=\"#{v}\"" if v}.join(" ")}>"
else
"Error processing input, expected syntax: {% img [class name(s)] [http[s]:/]/path/to/image [width [height]] [title text | \"title text\" [\"alt text\"]] %}"
end
end
end
end
Liquid::Template.register_tag('img', Jekyll::ImageTag)
What is the best way to create another custom tag for exhibiting the same functionality for the [<img>] element, but nested within a [<figure>] element and perhaps displaying the image alt description or an additional token as a [<figcaption>] element which could potentially include its own link? Or possibly even a series of class names for the element that say whether or not it should be centered or not.
In other words, I might want the output to be something like:
<figure class=center>
<img src="/contra.jpg" alt="One of the greatest nintendo games of all time">
<figcaption>Up Up Down Down Left Right Left Right B A B A Watch on Youtube</figcaption>
</figure>
Am I wrong to assume that it is possible to nest custom Liquid tags? I'm sure I could rewrite the existing code a second time and modify it slightly to handle the additional attribute for [<figcaption>], but this seems rather redundant and against DRY principles. And as it currently stands, I'm rather confused as to how I might account for a possible, additional token given that the existing class takes optional tokens itself.
What I needed to do was to create a Liquid Block, not a Liquid Tag. This solution allows one to nest other Liquid tags and even other Liquid blocks in theory, within the figure which is exactly what one would expect for a [<figure>] tag.
Since Markdown does not currently support HTML5, this Liquid based solution is a nice compromise.
# Example:
#
# {% fig This is my caption! http://site.com/link.html Link Caption %}
# {% img center http://site.com/images/mylinks.png A collection of my favorite links %}
# {% endfig %}
#
# Output:
#
# <figure class='center'>
# <img class="center" src="http://site.com/images/mylinks.png" title="A collection of my favorite links" >
# <figcaption>This is my caption!<a href='http://site.com/link.html'>Link Caption </a></figcaption>
#</figure>
#
#
module Jekyll
class FigureTag < Liquid::Block
include TemplateWrapper
CaptionUrl = /(\S[\S\s]*)\s+(https?:\/\/\S+)\s+(.+)/i
Caption = /(\S[\S\s]*)/
def initialize(tag_name, markup, tokens)
#title = nil
#caption = nil
if markup =~ CaptionUrl
#caption = "\n\t\t<figcaption>#{$1}<a href='#{$2}'>#{$3}</a></figcaption>\n\t"
elsif markup =~ Caption
#caption = "\n\t\t<figcaption>#{$1}</figcaption>\n\t"
end
super
end
def render(context)
output = super
fig = super.join
source = "\t<figure class='center'>\n\t\t"
markdown = RDiscount.new(fig.lstrip).to_html[/<p>(.+)<\/p>/i]
source += $1
source += #caption if #caption
source += "</figure>"
source = safe_wrap(source)
source
end
end
end
Liquid::Template.register_tag('fig', Jekyll::FigureTag)