0
0
Ruby on Railsframework~10 mins

ERB template syntax in Ruby on Rails - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - ERB template syntax
Start ERB Template
Read line
Check for ERB tags
Run Ruby
No Output
Next line or End
The ERB template reads each line, detects Ruby code tags, executes code, and inserts output if needed.
Execution Sample
Ruby on Rails
<h1>Welcome</h1>
<% name = "Alice" %>
<p>Hello, <%= name %>!</p>
This template sets a Ruby variable and inserts its value into HTML.
Execution Table
StepLine ReadERB TagActionOutput Produced
1<h1>Welcome</h1>NoneOutput HTML as is<h1>Welcome</h1>
2<% name = "Alice" %><% %>Run Ruby code, no output
3<p>Hello, <%= name %>!</p><%= %>Run Ruby, insert output<p>Hello, Alice!</p>
4End of templateNoneStop processing
💡 Reached end of template, all lines processed
Variable Tracker
VariableStartAfter Step 2Final
nameundefined"Alice""Alice"
Key Moments - 2 Insights
Why does <% %> not produce visible output but <%= %> does?
Because <% %> runs Ruby code without inserting anything into HTML, while <%= %> runs Ruby and inserts the result into the output, as shown in steps 2 and 3 of the execution_table.
What happens if you put Ruby code outside ERB tags?
Ruby code outside ERB tags is treated as plain text and output as is, not executed. ERB only runs code inside <% %> or <%= %> tags.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the output after step 2?
A"" (empty string)
B"Alice"
C<p>Hello, Alice!</p>
D<h1>Welcome</h1>
💡 Hint
Check the Output Produced column for step 2 in execution_table
At which step does the variable 'name' get assigned a value?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Look at the Action column in execution_table where Ruby code runs
If you change <%= name %> to <% name %> in line 3, what changes in the output?
AThe name 'Alice' will still appear in the output
BNothing will be output for that part
CAn error will occur
DThe whole line will be removed
💡 Hint
Compare the difference between <%= %> and <% %> tags in execution_table
Concept Snapshot
ERB template syntax:
- <% code %> runs Ruby code, no output
- <%= code %> runs Ruby and inserts output
- Lines without tags output as HTML
- Used to mix Ruby logic with HTML
- Output builds line by line as template processes
Full Transcript
ERB templates mix Ruby code with HTML. The template reads each line. If it finds <% %> tags, it runs Ruby code without output. If it finds <%= %> tags, it runs Ruby and inserts the result into the HTML output. Lines without tags are output as plain HTML. Variables set inside <% %> can be used later in <%= %> to show values. This process continues line by line until the template ends.