Created
January 10, 2011 04:38
-
-
Save levity/772363 to your computer and use it in GitHub Desktop.
simple templating
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/ruby | |
require 'yaml' | |
# DATA is a little-used feature of the Ruby language; it's a file handle | |
# whose contents are everything in the current file after the __END__. | |
# YAML is "Yet Another Markup Language". | |
data = YAML.load(DATA) | |
def url_for(entry_num) | |
"/photo_essay/#{entry_num}.html" | |
end | |
data[:entries].each_with_index do |entry, index| | |
index += 1 # start from entry 1 instead of 0 | |
# treat any word in the template surrounded by double curly brackets | |
# as a substitution variable. there are more full-fledged templating | |
# libraries, e.g. Liquid, but I wanted to keep this simple. | |
output = data[:template].gsub(/\{\{(\w+)\}\}/) do |match| | |
# $1 is the first matching group; you would also have $2, $3, etc. | |
# if the regex had more matching groups. | |
case $1 | |
when "next_url" | |
url_for(index == data[:entries].size ? 1 : index + 1) | |
else | |
entry[$1] | |
end | |
end | |
puts "entry #{index}" | |
puts output | |
# to save files: | |
# open("#{index + 1}.html", "w") {|file| file.write(output) } | |
end | |
__END__ | |
:entries: | |
- | |
photo: foo.jpg | |
blurb: this is a very short blurb | |
- | |
photo: bar.jpg | |
blurb: | |
Lorem ipsum dolor sit amet, consectetur adipisicing elit, | |
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. | |
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris | |
nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in | |
reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla | |
pariatur. Excepteur sint occaecat cupidatat non proident, sunt in | |
culpa qui officia deserunt mollit anim id est laborum. | |
- | |
photo: baz.jpg | |
blurb: hmm hmm hmm | |
:template: | |
<div class="entry"> | |
<img src="{{photo}}"/> | |
<div class="blurb"> | |
{{blurb}} | |
</div> | |
<a href="{{next_url}}">next entry</a> | |
</div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment