jekyll-seo-tag/lib/jekyll-seo-tag.rb

81 lines
1.9 KiB
Ruby
Raw Normal View History

2017-04-06 23:02:32 +00:00
require "jekyll"
2016-09-08 15:33:03 +00:00
require "jekyll-seo-tag/version"
2016-01-29 18:35:40 +00:00
2015-10-25 21:21:46 +00:00
module Jekyll
class SeoTag < Liquid::Tag
2017-04-08 18:20:21 +00:00
autoload :JSONLD, "jekyll-seo-tag/json_ld"
2017-04-07 21:01:20 +00:00
autoload :Drop, "jekyll-seo-tag/drop"
autoload :Filters, "jekyll-seo-tag/filters"
2015-10-25 21:21:46 +00:00
attr_accessor :context
2016-10-15 19:24:13 +00:00
# Matches all whitespace that follows either
# 1. A '}', which closes a Liquid tag
# 2. A '{', which opens a JSON block
# 3. A '>' followed by a newline, which closes an XML tag or
# 4. A ',' followed by a newline, which ends a JSON line
# We will strip all of this whitespace to minify the template
# We will not strip any whitespace if the next character is a '-'
# so that we do not interfere with the HTML comment at the
# very begining
MINIFY_REGEX = %r!(?<=[{}]|[>,]\n)\s+(?\!-)!
2016-02-09 23:48:24 +00:00
def initialize(_tag_name, text, _tokens)
2016-01-13 07:09:28 +00:00
super
@text = text
2016-01-13 07:09:28 +00:00
end
2015-10-25 21:21:46 +00:00
def render(context)
@context = context
template.render!(payload, info)
2015-10-25 21:21:46 +00:00
end
private
def options
{
2016-09-08 15:33:03 +00:00
"version" => Jekyll::SeoTag::VERSION,
2017-01-30 01:53:19 +00:00
"title" => title?,
}
end
2015-10-25 21:21:46 +00:00
def payload
{
2017-04-07 21:10:13 +00:00
"page" => context.registers[:page],
"site" => context.registers[:site].site_payload["site"],
2016-09-08 15:33:03 +00:00
"paginator" => context["paginator"],
2017-04-06 23:02:32 +00:00
"seo_tag" => drop,
2015-10-25 21:21:46 +00:00
}
end
2017-04-06 23:02:32 +00:00
def drop
2017-04-07 20:37:21 +00:00
@drop ||= Jekyll::SeoTag::Drop.new(@text, @context)
2016-02-21 19:25:15 +00:00
end
2015-10-25 21:21:46 +00:00
def info
{
:registers => context.registers,
2017-01-30 01:53:19 +00:00
:filters => [Jekyll::Filters],
2015-10-25 21:21:46 +00:00
}
end
2016-01-11 00:49:18 +00:00
def template
@template ||= Liquid::Template.parse template_contents
end
2015-10-25 21:21:46 +00:00
def template_contents
2016-02-09 23:48:24 +00:00
@template_contents ||= begin
2016-10-15 19:24:13 +00:00
File.read(template_path).gsub(MINIFY_REGEX, "")
2016-02-09 23:48:24 +00:00
end
2015-10-25 21:21:46 +00:00
end
def template_path
2016-02-09 23:48:24 +00:00
@template_path ||= begin
2016-09-08 15:33:03 +00:00
File.expand_path "./template.html", File.dirname(__FILE__)
2016-02-09 23:48:24 +00:00
end
2015-10-25 21:21:46 +00:00
end
end
end
2016-09-08 15:33:03 +00:00
Liquid::Template.register_tag("seo", Jekyll::SeoTag)