View Templates

Photo Share is supposed to be a web application for storing photos, but so far, the scaffolding shows only boring filenames. To make that change, we’ll work with view templates and controllers. Edit the file app/views/photos/show.html.erb, which is the view template created by the scaffold generator. If you have used template languages like ASP or JSP[3] before, you will recognize the syntax for embedding executable code within the HTML template. In this case, Rails is using ERb to embed Ruby code within an HTML template. As you recall, ERb will execute Ruby code between <% and %> without displaying anything. ERb will execute expressions between <%= and %> and place the results from executing that code into the template.

Insert this line at the beginning of app/views/photos/show.html.erb:

    <%= image_tag 'photos/' + @photo.filename %>

This line calls the Rails helper function image_tag, which generates an HTML <img> tag for the photo’s filename. By default, images are expected to be in the public/images directory of our Rails app. The photos on PhotoShare are in the public/images/photos directory, so prefix the filename with photos/. @photo, which we set in app/controllers/photos_controller.rb, contains the database record for the photos that we want to display:

def index @photos = Photo.find(:all) respond_to do |format| format.html # index.html.erb format.xml { render :xml => @photos } end end def show @photo = Photo.find(params[:id]) respond_to do |format| format.html ...

Get Rails: Up and Running, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.