代码之家  ›  专栏  ›  技术社区  ›  Joan Puigcerver

在Middleman中加载纯文本/标记文本(.txt/.md)文件

  •  0
  • Joan Puigcerver  · 技术社区  · 4 年前

    中间人自动加载以下内容 .json .yml data files 存在于 /data 文件夹。

    有没有办法加载的内容 任何 .txt .md 此文件夹中的文件?

    我找到了这个 extension ,但我不知道我怎么能做到这一点。

    例子

    给定此结构和以下文件:

    data/
    ├── foo.yml
    └── bar.txt
    
    • foo.yml :
    text: "I can load this text."
    
    • bar.txt
    I want to load this text.
    

    我可以访问 data.foo.text 并检索 I can load this text.

    我想访问 data.bar 并检索 I want to load this text.

    0 回复  |  直到 4 年前
        1
  •  0
  •   blackbiron    3 年前

    我不确定您通过读取txt数据(或markdown)想要实现什么。中间人数据不包含数组/哈希形式以外的数据。假设您想加载长(或格式化)文本,这是更好的IMO方式

    posts.yml:

    -
      title: First Post
      file: foo.txt
    -
      title: Second Title
      file: bar.txt
    

    在您看来:

    <% data.posts.each do |post| %>
      <%= post[:title] %>
      <%= simple_format(File.read("data/#{post[:file]}").html_safe) %>
    <% end %>
    
        2
  •  0
  •   Joan Puigcerver    3 年前

    我找到了一个解决方法,直到我弄清楚如何编写自己的扩展来加载纯文本文件。

    具有以下数据文件:

    • data/bar.yml :
    ---
    title: bar
    # Content in plain text can be placed after ---
    ---
    ## H2 test
    - Hello __world__!
    

    然后可以通过以下方式访问内容 data.bar.postscript :

    <div class="container">                 
        <h1><%= data.bar.title %></h1>
        <%= makrdown data.bar.postscript %> # In this case, I want to render it in Markdown
    </div>
    

    为了渲染Markdown,我在 config.rb :

    helpers do 
      def markdown(text=nil)
        text ||= yield
        return Redcarpet::Markdown.new(Redcarpet::Render::HTML, autolink: true, tables: true).render(text)
      end
    end