John123
John123

Reputation: 301

Learning Ruby ERB Templates

I'm trying to learn Ruby ERB Templates using the following guide: Tutorial Link

I am on the "very simple example" section with the following code:

require 'erb'

weekday = Time.now.strftime('%A')
simple_template = "Today is <%= weekday %>."

renderer = ERB.new(simple_template)
puts output = renderer.result()

I wanted to run this code to generate an html file so I created a file called

testing.html.erb

and ran the code with the following command:

erb testing.html.erb > new-file.html

When I did that through the terminal several errors popped up and the html file that was generated was blank. Here are the errors that I received: enter image description here

I was hoping someone could tell me what i was doing wrong. Am I forgetting something? Or am I not running the erb command correctly? Any help would be greatly appreciated. Thanks!

Upvotes: 1

Views: 2181

Answers (2)

Lukas Baliak
Lukas Baliak

Reputation: 2869

Your code will work if you send binding to the results method.

puts output = renderer.result(binding)

more about bindings: Ruby’s Binding Class (binding objects)

Upvotes: 1

ReggieB
ReggieB

Reputation: 8257

The code will run if you pass it to ruby. That is initiate it with this:

ruby testing.html.erb > new-file.html

The erb command expects to be passed an erb template file and not a piece of ruby code. It sees all the ruby code as just plain text, with just the insertion code <%= weekday %> needing to be interpreted as ruby code. So it tries to interpet weekday - but as it hasn't been defined it fails.

Try this and I think you may see what's happening:

Change the content of the file 'testing.html.erb' to:

require 'erb'

weekday = Time.now.strftime('%A')
simple_template = "Today is <%= Time.now %>."

renderer = ERB.new(simple_template)
puts output = renderer.result()

Then look at the output of erb testing.html.erb:

require 'erb'

weekday = Time.now.strftime('%A') simple_template = "Today is 2016-10-24 08:40:41 +0100."

renderer = ERB.new(simple_template)

Note that the whole file 'testing.html.erb' is the template.

Now look at the output of ruby testing.html.erb

Today is 2016-10-24 08:42:16 +0100.

Here the template is the content of the variable simple_template

Upvotes: 1

Related Questions