Adding Dynamic Content in Actions
Understand how to add dynamic content to Rails applications by embedding Ruby code in templates using ERB. Explore how controllers pass data to views, enabling flexible, interactive web pages that update on each request.
Making it dynamic
So far, our Rails application is pretty boring. It just displays a static page. To make it more dynamic, let’s have it show the current time whenever it displays the page.
To do this, we need to change the template file in the view, which will now need to include the time as a string. That raises two questions. First, how do we add dynamic content to a template? Second, where do we get the time from?
Dynamic content
We can create dynamic templates in Rails in many ways. The most common way, which we’ll use here, is to embed Ruby code in the template. That’s why the template file is named hello.html.erb. The .html.erb suffix tells Rails to expand the content in the file using a system called ERB.
ERB is a filter that is installed as part of the Rails installation. It takes an .erb file and outputs a transformed version. The output file is often HTML in Rails, but it can be anything. Normal content is passed through without being changed. However, content between <%= and %> is interpreted as Ruby code and is executed. The result of that execution is ...