How to generate pages for each tag in nanoc

六眼飞鱼酱① 提交于 2019-12-05 01:43:49
Denis Defreyne

You can use a preprocess block in your Rules file in order to generate new items dynamically. Here’s an example of a preprocess block where a single new item is added:

preprocess do
  items << Nanoc::Item.new(
    "some content here",
    { :attributes => 'here', :awesomeness => 5000 },
    "/identifier/of/this/item")
end

If you want pages for each tag, you need to collect all tags first. I’m doing this with a set because I do not want duplicates:

require 'set'
tags = Set.new
items.each do |item|
  item[:tags].each { |t| tags.add(t.downcase) }
end

Lastly, loop over all tags and generate items for them:

tags.each do |tag|
  items << Nanoc::Item.new(
    "",
    { :tag => tag },
    "/tags/#{tag}/")
end

Now, you can create a specific compilation rule for /tags/*/, so that it is rendered using a "tags" layout, which will take the value of the :tag attribute, find all items with this tag and show them in a list. That layout will look somewhat like this:

<h1><%= @item[:tag] %></h1>
<ul>
  <% items_with_tag(@item[:tag]).each do |i| %>
    <li><%= link_to i[:title], i %></li>
  <% end %>
</ul>

And that, in broad strokes, should be what you want!

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!