rubymiddlemanmiddleman-4

Avoid building identical pages with Middleman proxy


I am creating a static website with Middleman, referencing products parsed from a spreadsheet.

My table has these columns:

 _________________________________
| Product Name | Price | Category |
| Pet Food     |   $12 | Pets     |
| iPhone       |  $500 | Phone    |
| Pet toy      |   $25 | Pets     |
|______________|_______|__________|

I created pages that show all products in the Pets and Phone categories using a template called product_category.html. It creates a page for each unique category, eg. pets.html and phone.html.

The problem is that given the way I proceed, Middleman builds one category page for each product in the category, and then skips it as it is identical:

remote:           create     build/pets.html
remote:           identical  build/pets.html
remote:           create     build/iphone.html

Here is my sample for config.rb:

rows_by_categories = app.data.spreadsheet.sheet1.group_by { |row| row.category }

#Category Landings

app.data.spreadsheet.sheet1.each do |f|
  proxy "/#{f.category.to_s.downcase.strip.gsub(' ', '-').gsub(/[^\w-]/, '')}.html", "/product_category.html", locals: {
    f: {
      categorytitle: f.category,
      name: f.name,
      all_in_category: rows_by_categories[f.category],
      price: f.selling_price,
    },
  categories: rows_by_categories.keys,
  }, ignore: true
end

I understand the loop iterates on each line of my spreadsheet and recreates a page for the corresponding category. Yet the few tries I gave, eg. modifying app.data.spreadsheet.sheet1.each do |f| into rows_by_categories.each do |f| are unsuccessful. Any clue?


Solution

  • As mentioned I have no experience with middleman but I am going to try and help anyway.

    It appears that your main issue is that you are looping the individual items rather than the groups. Please try the below instead.

    rows_by_categories = app.data.spreadsheet.sheet1.group_by { |row| row.category }
    
    #Category Landings
    rows_by_categories.each do |category, rows|
        path_name = "/#{category.to_s.downcase.strip.gsub(' ', '-').gsub(/[^\w-]/, '')}.html" 
        row_data = rows.map do |row| 
            {
              categorytitle: row.category,
              name: row.name,
              price: row.selling_price,
            }
        end
        proxy path_name, "/product_category.html", locals: {
            products: row_data,
            categories: rows_by_categories.keys
         }, ignore: true
    end
    

    Here we loop through the categories and products will now be an Array of all the products in that category rather than a single product. This will, in my limited knowledge, create a single page for each category and give you a collection products that you can loop through