1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

middleman v4 の collection と resources 機能を使ってみる

1
Last updated at Posted at 2017-02-12

middlemn v4 では resources と collection というのが導入されたらしいのですが、公式ドキュメントを見てもいまいち分かりにくいです。どうやらわざわざextension で manipulate_resource_list() を使わなくても手軽にリソース操作ができるっぽいですね。

resources を使ってみる。

とりあえず、すべてのリソースに 'foo' というローカル変数を使えるようにしてみます。config.rb に

resources.each {|res|
  res.add_metadata(locals: {foo: "YES! FOO!!!"})
}

と書くだけで、*.html.erb で

foo? <%= foo %>

と使えるようです。確かに便利ですね。v3ではこれをするのには Middleman::Extension から派生させたクラスを作って manipulate_resource_list() を書いてそのクラスを Middleman::Extensions に register して activate して、、、という手順を踏まなければなりませんでしたから。

collection を使ってみる

ドキュメントのタグの例題が分かりにくいので、ここでは、**「見てほしい記事に mitene: 100 とかフロントマターにつけて大きい順に表示する」**というのをやってみたいと思います。

config.rb:

mitene = resources.select {|r| r.data.mitene }.sort_by {|r| r.data.mitene}.reverse

collection :mitene, mitene

というふうに、collection() を使って、あるシンボルに対して、resources から始まるチェーンから作られたオブジェクトを紐付けしてあげます。そうすると mitene.html.erb でそのシンボルを使って、

<h2>みてね!</h2>

<ul>
<% collection(:mitene).each do |res| %>
  <li><%= link_to(res.data.title, res) %></li>
<% end %>
</ul>

というふうに、集めておいたオブジェクトを呼び出せるようです。

また、config.rb:

mitene = resources.select {|r| r.data.mitene }.group_by {|r| r.data.mitene }
collection :mitene, mitene

とハッシュにしてあげて

<h2>みてね!順</h2>
<ul>
<% collection(:mitene).sort_by {|r, v| r}.reverse.each do |key, items| %>
<li><%= key %>
  <ul>
    <% items.each do |res| %>
    <li><%= link_to(res.data.title, res) %></li>
    <% end %>
  </ul>
<% end %>
</ul>

と受け取ることも出来ます。

ちょっとリソースに手を加えたり、特定の条件のリソースを集めておいてテンプレートで使うということが手軽にできそうな感じです。

また分かり次第追記していきます。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?