I am making a comic book collection app using Middleman.
I am able to get different information from a YAML file and render it in a .erb file.
Now, I created a date using yaml like this:
date: 1977-08-01
I tried looking around the web on how to render it in different format, but I can't find ANYTHING...
Per example, I have a title field, in my yaml document, that goes like this:
title: "Uncanny X-Men"
So I render it in my erb document using this:
<%= comic["title"] %>
But how do I get, let's say, to print the month from my date? Impossible to find any kind of information... I do get how to use different aspects of dates in either ruby or yaml, but not how to render a date FROM yaml to ruby :(
Thanks!
You need to parse your date
value in the YAML file into a Ruby date class, first make sure to surround your date values in the YAML file with quotes like so:
date: '1977-08-01'
and then to parse:
<%= Date.parse(comic["date"]) %>
and to get the month you would add .month
like so:
<%= Date.parse(comic["date"]).month %>
that will give you the number 8
if you want more customization to the way your month look like you should look into strftime, if so you wouldn't even need to use .month
.
Ideally to DRY things up, you would create a helper in the config.rb
# Methods defined in the helpers block are available in templates
helpers do
def format_date(date_txt)
date = Date.parse(date_txt)
date.strftime("%B")
end
end
And later you can call it inside your template like so:
<%= format_date(comic["date"]) %>
I hope that helps.