Adding Dynamic Content in Actions

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 converted into a string, and that value is substituted in the file in place of the <%=...%> sequence. For example, let’s change hello.html.erb to display the current time:

Get hands-on with 1400+ tech skills courses.