helcim
helcim

Reputation: 819

How to link dynamically generated pages in MIddleman?

I am generating my dynamic pages with the following in config.rb

data.generated.each do |i|
  proxy "#{i.id}.html", "/generated/template.html", :locals => { :i => i }, :ignore => true
end

and a template in source/generated/template.html.erb

<% i = locals[:i] %>
<h1><%= i.title %></h1>

How can I create links to next and previous of these generated pages dynamically?

Upvotes: 1

Views: 278

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

There is an easy way to generate all pages save for the first and last ones:

data.generated.each_cons(3) do |prev, curr, nxt|
  proxy "#{curr.id}.html",
        "/generated/template.html",
        locals: { prev: prev, curr: curr, next: nxt },
        ignore: true
end

The above would start with curr being the second page. I can’t find the quick solution to handle these corner cases in an elegant manner, so we’d just produce these pages manually:

def generate_page prev, curr, nxt
  proxy "#{curr.id}.html",
        "/generated/template.html",
        locals: { prev: prev, curr: curr, next: nxt },
        ignore: true
end

data_generated = data.generated
data_generated.each_cons(3).with_index do |(prev, curr, nxt), idx|
  generate_page(nil, prev, curr) if idx == 0
  generate_page(prev, curr, nxt)
  generate_page(curr, nxt, nil) if idx == data_generated.size
end

<% prev, curr, nxt = locals.values_at(*%i|prev curr next|) %>
<h1><%= curr.title %></h1>

  <a href="<%= prev.id %>.html">⇐ <%= prev.title %></a> |
  <a href="<%= nxt.id %>.html"><%= nxt.title %> ⇒</a>

It might be needed to apply the additional check for nxt/prev not being nil is required around building links.

Upvotes: 1

Related Questions