如何通过JSON文件动态生成页面

时间:2015-05-27 10:47:31

标签: ruby middleman

我需要通过数据JSON文件创建数百个静态产品 html页面

首先,我将从 data.json

加载所有产品信息

然后,将其加载到产品页面模板

最后,将其应用于布局模板

我怎样才能在中间人

中完成它

或者,如果我可以通过任何现有宝石生成产品页面的所有产品静态页面

data.json

```json
[
  {
    product_name: "~~"
    product_images_link: "~~"
    product_price: "~~"
    product_description: "~~"
  },
  {
    product_name: "~~"
    product_images_link: "~~"
    product_price: "~~"
    product_description: "~~"
  }
]

```

布局

%html
  %head
    %link{:href => "/stylesheets/bootstrap.css", :rel => "stylesheet", :type => "text/css"}/
  %body.overview
    = yield
    %script{:src => "/javascripts/overview.js"}

产物的页

.head
  .product_info
    %h1= product_name
    %h1= product_price
    = product_description
  .image
    %img{:alt => "", :src => "#{product_images_link}"}/

1 个答案:

答案 0 :(得分:1)

看起来你正在使用Haml,你可以这样做http://haml.info/docs/yardoc/Haml/Engine.html

class SomeClass
  def generate_product_files
    products.each do |product|
      save_product_as_html(product)
    end
  end

  private

  def save_product_as_html(product)
    html = product_template_engine.render(
      Object.new,
      product_name:        product.fetch(:name),
      product_price:       product.fetch(:price),
      product_description: product.fetch(:description),
      product_images_link: product.fetch(:product_images_link)
    )

    file_path = "products/product-#{ product.fetch(:id) }"

    File.open(file_path, 'w') do |file|
      file.puts(html)
    end
  end

  def product_template_engine
    @product_template_engine ||= Haml::Engine.new(File.read('some_template.html.haml'))
  end
end