【问题标题】:How to get the raw "content" from all pages如何从所有页面获取原始“内容”
【发布时间】:2014-10-02 21:05:04
【问题描述】:

我正在尝试为我的 Middleman 网站创建一个索引文件,并希望在该文件中包含我网页的原始“内容”。即

/source/mypage.md:

---
title: My Page
---
# This is my page
With *my markdown*

/source/myotherpage.md:

---
title: My Other Page
---
# Here is my other page

我想要在/source/site_index.json.erb 的第三页,当输出看起来像这样时:

 [
   {'title': 'My Page', 'body': '#This is my page\nWith *my markdown\n'},
   {'title': 'My Other Page', 'body': '#Here is my other page\n'}
 ]

我可以使用类似的方法获取标题等,但我不知道如何获取原始正文:

[
  <% sitemap.resources.select{|resource| resource.content_type == 'text/html; charset=utf-8' unless resource.data.ignore }.each do |resource| %>
    {
      "title": <%= resource.data.title.to_json %>,
      "body": <%= nil %>
    } ,
  <% end %>
]

【问题讨论】:

    标签: ruby sitemap sprockets middleman


    【解决方案1】:

    resource 对象有一个指向源文件 (source_file) 的指针,您可以直接读取文件内容:

    [
        <%
        pages = sitemap.resources.select{|resource| resource.content_type == 'text/html; charset=utf-8' unless resource.data.ignore }
        pages.each_with_index do |resource, index|
            file = File.open(resource.source_file, 'r')
            content = file.read
        %>
        {
            "title": <%= resource.data.title.to_json %>,
            "body": <%= content.to_json %>
        } <%=',' unless( index == pages.length-1) %>
        <% end %>
    ]
    

    这对我有用,用 Middleman 3.3.3 测试过。

    【讨论】:

      【解决方案2】:

      之前从未使用过 Middleman,但您尝试过 resource.render 吗?

      根据http://rubydoc.info/gems/middleman-core/Middleman/Sitemap/Resource#render-instance_method 的文档,它似乎应该可以工作。

      另一个潜在的线索是在https://github.com/middleman/middleman-sitemap-api/blob/master/lib/middleman-sitemap-api/extension.rb#L122raw_body_content 的以下引用

      希望对你有帮助

      【讨论】:

      • resource.render 返回最终的 HTML 输出,而不是原始源(在我的例子中是 Markdown)。 raw_body_content 看起来很有希望,但需要引用我没有看到的“中间人”变量。
      • 不,正如我上面解释的,有几个问题。
      • 啊,好吧,对不起 - 我在你编辑之前看到了你的评论。让我再看几眼..
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多