part-3.jpg

Learn Sails.js - Part 3

🛈

Aye, aye, Boatswain! Let’s get this ship looking respectable. It’s time to hoist the banners and polish the quarterdeck.


Part 3: Designing the Quarterdeck (Views & Assets)

  • Current Rank: Boatswain
  • Objective: To learn how to make your application presentable by creating custom web pages and styling them with CSS via Sails’ Asset Pipeline.

The Captain’s Briefing (Background and Theory)

So far, our ship can respond to hails, but only by shouting back raw data (JSON). That’s fine for ship-to-ship communication, but it’s not very welcoming for distinguished visitors who expect to come aboard and see a polished deck. This module is about creating that polished deck: the View layer.

From Data to Decks: res.view()

In the last module, we used res.json() to send back data. To send back a full HTML page, we use a different command: res.view(). When you call res.view('some-page'), Sails looks inside your views/pages/ folder for a file named some-page.ejs and sends it to the user’s browser as a web page.

EJS: The Magic Parchment

The files inside your views/ folder are not plain HTML. They are .ejs files, which stands for Embedded JavaScript. Think of EJS as a magic parchment: it looks and feels like normal HTML, but you can embed special tags into it to print dynamic data.

  • <%= data %>: This tag is like a magic quill. It takes a variable from your controller and writes its value directly onto the page. For example, if you pass { captainName: 'Grace O'Malley' } from your controller, <%= captainName %> in your view file will become Grace O'Malley in the final HTML.

The Master Blueprint: Layouts

Building every single page from scratch would be tedious. You’d have to copy and paste your navigation bar, header, and footer on every page. Sails solves this with a layout file.

Look in views/layouts/layout.ejs. This is your master ship blueprint. It contains the common HTML structure for your entire site (<html>, <head>, <body>, etc.). Notice the special tag somewhere in the middle: <%- body %>.

When you call res.view('pages/homepage'), Sails first renders homepage.ejs, then takes the resulting HTML and injects it into the layout.ejs file right where <%- body %> is. This way, you only need to define your main structure once!

Paint and Flags: The Asset Pipeline

How do you add styling (CSS), front-end interactivity (JavaScript), or images? You place these files into the assets/ directory.

  • Stylesheets go in assets/styles/.
  • Client-side JavaScript goes in assets/js/.
  • Images go in assets/images/.

This isn’t just a folder for storage. Sails has a powerful Asset Pipeline. When you run sails lift, Sails automatically scans these folders. It will compile, combine, and minify these files for you (in production), and most importantly, it will automatically inject the necessary <link> and <script> tags into your layout.ejs file. You don’t need to manually link to your stylesheets; just drop them in the right folder, and Sails handles the rest.


Key Concepts Checklist

  • res.view(): The response method to render a view and send it as an HTML page.
  • views/: The directory where all .ejs template files are stored.
  • EJS (Embedded JavaScript): The template language for mixing data with HTML.
  • <%= %>: The EJS tag for outputting data into the HTML.
  • Layouts: The master template (views/layouts/layout.ejs) that wraps your individual view files.
  • Asset Pipeline: The system that automatically manages and includes files from the assets/ directory.

Mission Log: Quest - “The Captain’s Log”

Our ship needs a proper logbook. We will create a new page at /logbook, display the Captain’s name dynamically, and give the page some custom styling.

  • Task 1: The New Harbor Master’s Order (Create the Controller Action)

    1. Open your api/controllers/CaptainController.js file.
    2. Add a new action called logbook below your greet action.

      module.exports = {
      
        greet: function(req, res) { 
          /* ... your existing greet action ... */
        },
      
        // Add this new action
        logbook: function(req, res) {
          // We're passing an object with data to the view.
          // The view will be able to access `captainName`.
          return res.view('pages/logbook', {
            captainName: 'Blackheart Beatrice'
          });
        }
      
      };
      
  • Task 2: Crafting the Page (Create the View File)

    1. In your code editor, create a new file.
    2. Save it inside the views/pages/ directory as logbook.ejs.
    3. Add the following content to this file. Notice how we use the <%= %> tag to display the captainName variable we’re passing from the controller.

      <div id="logbook">
        <h1>Captain's Log</h1>
        <h2>A Record for Captain <%= captainName %></h2>
        <p>
              Stardate: 47634.4. The ship is performing flawlessly. The crew is in high spirits. 
              We have successfully established our first custom route and are now preparing to chart the vast oceans of the web.
        </p>
      </div>
      
  • Task 3: Charting the New Lane (Create the Route)

    1. Open config/routes.js.
    2. Add a new route to direct traffic from the /logbook URL to your new action.

      // ... previous routes
      'GET /hail': 'CaptainController.greet',
      'GET /logbook': 'CaptainController.logbook', // <-- ADD THIS LINE
      '/': { view: 'pages/homepage' },
      // ... rest of the file
      
  • Task 4: Painting the Cabin (Add Custom CSS)

    1. In the assets/styles/ directory, create a new file named custom.css.
    2. Add the following CSS rule to give your logbook page some style.

      body {
        /* A nice, light blue background for our voyage */
        background-color: #f0f8ff; /* AliceBlue */
      }
      
      #logbook {
        border: 1px solid #004d99;
        padding: 20px;
        margin: 40px;
        background-color: #fff;
        border-radius: 5px;
      }
      
  • Task 5: The Grand Tour

    1. Start your server with sails lift (or restart it if it was running).
    2. Open your browser and navigate to http://localhost:1337/logbook.
    3. You should see your new logbook page, complete with the captain’s name “Blackheart Beatrice” and the new light-blue background color. The asset pipeline automatically linked your custom.css file for you!

Mission Debrief (Review & Outcomes)

Splendid work, Boatswain. The quarterdeck is immaculate. You have successfully separated logic from presentation.

  • Your Controller handled the request and decided what data to show.
  • Your View handled the presentation and decided how to show it.
  • The Asset Pipeline handled the styling, linking your CSS automatically.

This is the MVC pattern in its full glory. Your application is no longer just a data machine; it’s a presentable web application. You can now create as many pages as you wish, each with its own-logic and styling.


Rewards

  • +150 Doubloons
  • Achievement Unlocked: You’ve created a styled web page with dynamic data. The ship’s banners are flying high!
    • Badge Earned: Raise the Banners 🎨