Views and View Engines
Homework
- View Engines
- Using template engines with Express
- EJS
- How To Use EJS to Template Your Node Application
- Search: node ejs tutorial
- Reference: EJS home page
- Reference: EJS tag reference
- Pug
- Search: node pug tutorial
- Handlebars
- Search: node handlebars tutorial
response.locals
- res.locals from Express documentation
Morning reflection
-
Listing global npm packages
$ npm list -g --depth 0
Housekeeping
- Final Project: Group Charter
- Semi-colons
in-class
code- finished examples will be pushed to
sample-code
throughout the week.
- finished examples will be pushed to
1. View Engines
Learning Objectives
- Understand the purpose of a view engine.
- Install
ejs
as a project dependency. - Set an express app view engine.
- Create a view template.
- Render an view template to html with
app.get()
andresponse.render()
.
Terminology
- View engine
- A syntax parser that replaces variables in a template file with values, and transforms the template into an HTML file sent to the client.
Materials
- Sample Code: EJS Getting Started
- Activity: Step 1 - Create views
- Article: How To Use EJS to Template Your Node Application for the basics.
Key Takeaways
See Takeaways in EJS Getting Started.
2. EJS including template partials
Learning Objectives
- Create a template partial.
- Include a template partial in another file.
Materials
- Sample Code Activity: Step 2 - Create view partials
3. Injecting global variables with response.locals
Learning Objectives
- Inject global variables with
response.locals
. - Output a variable with
<%= %>
.
Materials
- Sample Code Activity: Step 3 - Inject global variables
4. Injecting local variables with response.render()
Learning Objectives
- Inject local variables with
response.render()
. - Output a variable with
<%= %>
.
Materials
- Sample Code Activity: Step 4 - Inject local variables
Open lab-time
- Using today’s activity try converting one or more of your current/past projects.
- Final Project Groups. Begin your Group Charter if you haven’t already.
- Level-up: Generate navigation for your views dynamically:
- Create a local module that exports an array objects that describe the information needed for your nav links:
linkURL
linkText
- Load this module with
require()
. - Pass the nav object to
res.locals
. -
Using EJS, use
<% %>
tags to loop this object and generate your nav menu. The code should look something like this:<ul> <% products.forEach(function(product) { %> <li> <strong><%= product.name %></strong>: <em><%= product.price %></em> </li> <% }); %> </ul>
- Create a local module that exports an array objects that describe the information needed for your nav links:
Lab Time Demo: ???
Dailies
- Submit today’s Codepen/repo/gist to the Dailies section (in Assessments) in Brightspace.