Give an array in Jekyll’s _data
structure:
_data/array.yml
- id: id1
name: name1
- id: id2
name: name2
How can I create a block tag that will lookup the object with the specific id and pass in as context inside the block tag. Like this
{% item id1 %}
<p>{{ site.data.array.length }}</p>
<p>{{ item.name }}</p>
{% enditem %}
I’ve made this so far:
module Jekyll
class ItemBlock < Liquid::Block
def initialize(tag_name, markup, tokens)
super
@tag = markup
end
def render(context)
jekyllSite = context.registers[:site]
items = jekyllSite.data['array'].select { |item|
item['id'] == context[@tag.strip]
}
context.environments.first['item'] = items.first
super
end
end
end
Liquid::Template.register_tag("item", Jekyll::ItemBlock)
But now the item
is available to the whole template even outside the block.
{% item id1 %}
<p>{{ site.data.array.length }}</p>
<p>{{ item.name }}</p>
{% enditem %}
<p>{{ item.name }}</p>
Is this the correct approach?