【问题标题】:how do I generate pages dynamically by a JSON file如何通过 JSON 文件动态生成页面
【发布时间】:2015-05-27 10:47:31
【问题描述】:

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

首先,我将从 data.json

中加载所有产品信息

然后,将其加载到product-page模板中,

最后,应用到layout模板

我怎么能在middleman中完成它

或者,如果我可以通过任何现有 gem 生成带有 product-page 的所有产品静态页面

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}"}/

【问题讨论】:

  • 如果您需要从模板生成文本,您是否考虑过尝试erb
  • 嗨@floum 有没有关于erb 生成的简单教程或链接?
  • 查看这个优秀的指南:stuartellis.eu/articles/erb

标签: ruby middleman


【解决方案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

【讨论】:

    猜你喜欢
    • 2019-07-31
    • 2020-08-06
    • 2018-07-28
    • 1970-01-01
    • 1970-01-01
    • 2011-07-18
    • 1970-01-01
    • 1970-01-01
    • 2011-05-14
    相关资源
    最近更新 更多