0
0
Ruby on Railsframework~15 mins

ERB template syntax in Ruby on Rails - Deep Dive

Choose your learning style9 modes available
Overview - ERB template syntax
What is it?
ERB template syntax is a way to embed Ruby code inside HTML files to create dynamic web pages. It lets you mix plain HTML with Ruby code that runs on the server before the page is sent to the browser. This makes web pages change based on data or user actions. ERB stands for Embedded Ruby.
Why it matters
Without ERB, web pages would be static and could not show changing information like user names or lists from a database. ERB solves the problem of mixing code and design in one file, making it easier to build interactive websites. It lets developers write Ruby code directly in HTML, so pages can update automatically based on logic or data.
Where it fits
Before learning ERB, you should know basic Ruby programming and HTML structure. After ERB, you can learn about Rails controllers and models that provide data to templates. Later, you might explore JavaScript frameworks for client-side interactivity or advanced Rails view helpers.
Mental Model
Core Idea
ERB lets you write Ruby code inside HTML to create web pages that change dynamically on the server before reaching the browser.
Think of it like...
ERB is like a chef preparing a meal in the kitchen (server) by mixing ingredients (HTML) with spices (Ruby code) before serving the dish (web page) to the customer (browser).
HTML with embedded Ruby code:

<html>
  <body>
    <h1>Welcome, <%= user_name %>!</h1>
    <% if logged_in %>
      <p>You have <%= notifications_count %> new messages.</p>
    <% else %>
      <p>Please log in to see your messages.</p>
    <% end %>
  </body>
</html>
Build-Up - 7 Steps
1
FoundationBasic ERB tags and usage
🤔
Concept: Learn the two main ERB tags: <%= %> for output and <% %> for code execution without output.
ERB uses two types of tags: - <%= Ruby code %> inserts the result of the Ruby code into the HTML. - <% Ruby code %> runs Ruby code but does not insert anything into the HTML. Example:

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

<% if Time.now.hour < 12 %>

Good morning!

<% end %>
Result
The page shows the current day and, if before noon, displays 'Good morning!'.
Understanding the difference between output and non-output tags is key to controlling what appears on the page.
2
FoundationEmbedding Ruby variables in HTML
🤔
Concept: Use ERB to insert Ruby variables directly into HTML content.
You can define Ruby variables in your controller and use ERB to show them in the view: Controller sets: @user_name = 'Alice' In ERB:

Hello, <%= @user_name %>!

Result
The page displays: Hello, Alice!
ERB connects Ruby data with HTML, making pages personalized and dynamic.
3
IntermediateConditional logic in ERB templates
🤔Before reading on: Do you think ERB can handle Ruby if-else statements directly inside HTML? Commit to yes or no.
Concept: ERB supports Ruby control flow like if-else to show or hide parts of the page based on conditions.
You can write Ruby conditionals inside <% %> tags: <% if @logged_in %>

Welcome back!

<% else %>

Please sign in.

<% end %>
Result
Depending on @logged_in, the page shows either a welcome message or a sign-in prompt.
Using Ruby logic inside templates lets you customize page content dynamically.
4
IntermediateLooping with ERB for lists
🤔Before reading on: Can ERB loop over arrays to create repeated HTML elements? Commit to yes or no.
Concept: ERB can use Ruby loops like each to generate repeated HTML for collections.
Example:
    <% @items.each do |item| %>
  • <%= item %>
  • <% end %>
Result
The page shows a list with each item inside a
  • tag.
  • Loops in ERB help build lists or tables dynamically from data arrays.
    5
    IntermediateEscaping HTML in ERB output
    🤔
    Concept: ERB automatically escapes HTML in output to prevent security risks like code injection.
    When you use <%= %>, ERB escapes special HTML characters like < and > by default. Example: <%= '' %> This will show the script tags as text, not run them.
    Result
    The browser displays the script tags as text, not as executable code.
    Automatic escaping protects users from malicious code and keeps pages safe.
    6
    AdvancedUsing ERB with partials and layouts
    🤔Before reading on: Do you think ERB templates can include other templates to reuse code? Commit to yes or no.
    Concept: ERB supports partial templates and layouts to organize and reuse view code efficiently.
    Partials are small ERB files included in other templates: <%= render 'header' %> Layouts wrap views with common HTML structure. This keeps code DRY (Don't Repeat Yourself).
    Result
    Pages share common headers, footers, and structure without repeating code.
    Knowing partials and layouts helps build maintainable and scalable web apps.
    7
    ExpertERB template rendering internals
    🤔Before reading on: Does ERB compile templates into Ruby code before rendering? Commit to yes or no.
    Concept: ERB templates are compiled into Ruby methods that run to produce HTML output at runtime.
    When Rails renders an ERB file, it converts it into Ruby code with embedded print statements. This compiled code runs efficiently and caches results for speed. Understanding this helps debug complex rendering issues.
    Result
    Templates render quickly and can be debugged by inspecting generated Ruby code.
    Knowing ERB compiles templates clarifies performance and debugging behavior.
    Under the Hood
    ERB works by parsing the template file and converting the embedded Ruby code into Ruby method calls. The <%= %> tags become Ruby print statements that insert output into the HTML string. The <% %> tags become Ruby code executed without output. This compiled Ruby code runs on the server to produce the final HTML sent to the browser.
    Why designed this way?
    ERB was designed to keep HTML and Ruby code together for easy web page creation. Compiling templates into Ruby code improves performance by avoiding repeated parsing. The syntax is simple and close to HTML, making it easy for designers and developers to collaborate.
    ERB Template File
      │
      ▼
    Parser converts tags
      │
      ▼
    Ruby code with print statements
      │
      ▼
    Ruby interpreter runs code
      │
      ▼
    Generated HTML output
      │
      ▼
    Sent to browser
    Myth Busters - 4 Common Misconceptions
    Quick: Does <%= %> tag run Ruby code without showing anything on the page? Commit to yes or no.
    Common Belief:Some think <%= %> runs code but does not produce output on the page.
    Tap to reveal reality
    Reality:<%= %> runs Ruby code and inserts its result into the HTML output.
    Why it matters:Misunderstanding this causes confusion about why some code outputs text and some does not.
    Quick: Can ERB templates run JavaScript code directly on the server? Commit to yes or no.
    Common Belief:People sometimes believe ERB can execute JavaScript code inside templates on the server.
    Tap to reveal reality
    Reality:ERB only runs Ruby code on the server; JavaScript runs in the browser after the page loads.
    Why it matters:Confusing server-side and client-side code leads to bugs and security issues.
    Quick: Does ERB automatically sanitize all user input to prevent security risks? Commit to yes or no.
    Common Belief:Many assume ERB always protects against all injection attacks automatically.
    Tap to reveal reality
    Reality:ERB escapes HTML by default in <%= %> but does not sanitize all user input or prevent all vulnerabilities.
    Why it matters:Relying solely on ERB escaping can leave apps vulnerable if developers do not validate and sanitize inputs properly.
    Quick: Is it safe to put complex business logic inside ERB templates? Commit to yes or no.
    Common Belief:Some think putting all logic in ERB templates is fine for simplicity.
    Tap to reveal reality
    Reality:Complex logic belongs in controllers or models; ERB should focus on presentation.
    Why it matters:Mixing logic and presentation makes code hard to maintain and debug.
    Expert Zone
    1
    ERB templates can be precompiled and cached to improve performance in production environments.
    2
    Using safe navigation operators and helper methods inside ERB prevents common nil errors and keeps templates clean.
    3
    ERB allows custom delimiters and trim modes to control whitespace and output formatting precisely.
    When NOT to use
    ERB is not ideal for highly interactive client-side features; use JavaScript frameworks like React or Vue instead. For APIs or JSON responses, use serializers or builders rather than ERB. Also, avoid putting heavy logic in ERB; keep it in Ruby classes.
    Production Patterns
    In production Rails apps, ERB templates are organized with layouts and partials for reuse. Helpers encapsulate common view logic. Templates are cached for speed. Developers use view components or presenters to keep ERB clean and maintainable.
    Connections
    MVC architecture
    ERB is the View layer in MVC, displaying data from Models via Controllers.
    Understanding ERB as the View clarifies how data flows and separates concerns in web apps.
    Template engines in other languages
    ERB is similar to JSP in Java or EJS in JavaScript, all embedding code in HTML.
    Knowing ERB helps grasp how server-side rendering works across different web frameworks.
    Print media layout design
    Like print designers combine text and images in layouts, ERB combines code and HTML to create pages.
    This connection shows how ERB balances structure and dynamic content like a designer balances fixed and variable elements.
    Common Pitfalls
    #1Putting complex Ruby logic directly inside ERB templates.
    Wrong approach:<% if user && user.orders.count > 0 && user.orders.last.status == 'pending' %>

    You have pending orders.

    <% end %>
    Correct approach:<% if user_has_pending_orders? %>

    You have pending orders.

    <% end %>
    Root cause:Misunderstanding that ERB should focus on presentation, not business logic.
    #2Using <% %> tag when output is needed, causing missing content.
    Wrong approach:<% @user_name %> logged in.
    Correct approach:<%= @user_name %> logged in.
    Root cause:Confusing code execution tag <% %> with output tag <%= %>.
    #3Not escaping user input, leading to security risks.
    Wrong approach:<%= params[:comment] %>
    Correct approach:<%= h(params[:comment]) %>
    Root cause:Assuming ERB always escapes output automatically without explicit escaping or sanitization.
    Key Takeaways
    ERB lets you embed Ruby code inside HTML to create dynamic web pages that change based on data and logic.
    The two main ERB tags are <%= %> for output and <% %> for running code without output.
    ERB templates support Ruby control flow like conditionals and loops to customize page content.
    ERB automatically escapes HTML output to protect against injection attacks but does not replace full input sanitization.
    Keeping complex logic out of ERB and using partials and layouts leads to cleaner, maintainable web applications.