Reputation: 3628
I'm following this demonstration of building custom liquid tags.
I want to create a tag that takes the image of a given post and returns an image tag with the path to its equivalent thumbnail.
Say the frontmatter for a post looks like this:
---
title: Build a plugin
layout: post
image: plugin.jpg
---
My tag would look like this:
{% thumb_for post.image %}
The desired output would be:
<img src="https://example.com/images/thumbs/plugin.jpg">
My attempt so far looks like this:
module Jekyll
class RenderThumbTag < Liquid::Tag
def initialize(tag_name, image, tokens)
super
@image = image
end
def render(context)
"<img src='#{context["site"]["url"]}/images/thumbs/#{@image}'>"
end
end
end
Liquid::Template.register_tag('thumb_for', Jekyll::RenderThumbTag)
However, the rendered tag ends up as http://example.com/images/thumbs/post.image
. Obviously I want post.image
to evaluate to the file name. What steps do I need to take? (Or have I got Liquid all wrong?)
I realise that my main problem is that I don't know how to reference the current iteration in this posts
loop:
{% for post in site.posts %}
<li class="post">
{% thumb_for %}
</li>
{% endfor %}
thumb_for
should return the thumbnail tag for each post
in posts
.
Of course, I should define thumb
on individual posts. I think I need to understand how to define custom variables for specific page types.
Upvotes: 0
Views: 298
Reputation: 8417
Assuming you only need the front matter variable, and any argument to the custom tag is to be ignored, this should do the job:
module Jekyll
class RenderThumbTag < Liquid::Tag
def render(context)
page = context.registers[:page]
"<img src='/images/thumbs/#{page.image}'>"
end
end
end
Liquid::Template.register_tag('thumb_for', Jekyll::RenderThumbTag)
You would invoke the tag like this:
{% thumb_for %}
BTW, I provide sample templates for Jekyll plugins on my blog.
Upvotes: 0