Load plain/markdown text (.txt/.md) files in Middleman

90 views Asked by At

Middleman automatically loads the contents of .json or .yml data files that exist in the /data folder.

Is there any way to load the contents of any .txt or .md file inside this folder?

I found this extension, but I don't see how I can achieve that.

Example

Given this structure and the following files:

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

I can access data.foo.text and retrieve I can load this text.

I want to access data.bar and retrieve I want to load this text.

2

There are 2 answers

0
blackbiron On

i'm not sure what you're trying to achieve by reading the txt data (or markdown). middleman data is not intended to contain data other than array/hash form. assuming you want to load long (or formatted) text, this is better way IMO

posts.yml:

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

and in your view:

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

I found a workaround until I figure out how to write my own extension for loading plain text files.

Having the following data file:

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

And then the content can be accessed with 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>

For rendering the Markdown I defined a helper function in 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