External Links Hyperlinking to an External Website
In this demonstration, I will show how to create a hyperlink that links to a webpage that is external to the web app (i.e., a webpage that is not part of the app).
General Steps
In general, the steps for adding a hyperlink that links to an existing webpage within a web app are as follows.
-
Step 1 Find the External Webpage’s URL. This step locates the URL for the external webpage to which we wish to link.
-
Step 2 Add the Link. This step adds to a webpage the hyperlink to the external webpage using a view-helper method.
Adding to the Billy Books Home Page a Hyperlink to Goatlandia.org
To demonstrate the steps for adding a hyperlink that links to a webpage that is external to the web app, we will be adding to the home page of the Billy Books bookstore base app a hyperlink to the Goatlandia.org website, as illustrated in Figure 1.
Step 1 Find the External Webpage’s URL
To find the URL of the external webpage, we open the Goatlandia.org website in our web browser, and we click on the location bar of the web browser to expand the full URL, as illustrated in Figure 2.
Step 2 Add the Link
To update the home page with a hyperlink to the external webpage, as shown in Figure 1, we add HTML and embedded Ruby to the home page’s view template, app/views/pages/home.html.erb
, like this:
<h1>Welcome to Billy Books!</h1>
<p>
Come visit us at 7107 Juniper Road Fairbend, TN, 37062!
</p>
<p>
Store Hours:
</p>
<ul>
<li>Monday: 10am - 7pm</li>
<li>Tuesday: 10am - 7pm</li>
<li>Wednesday: 10am - 7pm</li>
<li>Thursday: closed</li>
<li>Friday: 10am - 7pm</li>
<li>Saturday: 12pm - 6pm</li>
<li>Sunday: closed</li>
</ul>
<p>
10% of our profit goes to the
<%= link_to 'Goatlandia Farm Animal Sanctuary',
'https://www.goatlandia.org',
target: '_blank'
%>.
</p>
The link_to
method is a view helper that returns a string containing the HTML code for a hyperlink (specifically, an <a>
element). Because the call to link_to
is embedded within a <%= … %>
tag (note the =
), the HTML string returned by the call will be inserted directly into the webpage. The link_to
call takes three arguments. The first argument is the hyperlink text that will appear on the webpage. The second argument is the URL of the external webpage that is the destination of the hyperlink. The third argument, target: '_blank'
, adds a target="_blank"
attribute to generated <a>
element, which makes it so that clicking the link opens the external webpage in a new browser tab.
Test It!
To test that this step was completed correctly, we run the web app (as per the steps in the running apps demo), and we open the URL http://localhost:3000/home in our web browser. The webpage displayed should look exactly like Figure 1. Clicking on the hyperlink should open the Goatlandia.org home page in a new browser tab.
Conclusion
Following the above steps, we have now added to the home page of the Billy Books bookstore app a link to the Goatlandia.org website.