Rendering HTML and Templates

  • look for examples of the things covered in these notes in the repo: the-web-developer-bootcamp /11_express/ejs_demo

Using res.render()

  • allows us to save our html in its own file and pass it to res to be rendered
  • if we don't want it to send the same exact page every time, we need dynamic html files that are called EJS templates

EJS

  • stands for Embedded Javascript
  • it lets us embed javascript code inside of templates
  • use or <%= js content %> or <% js content %> to tell ejs to treat whatever is inside as javascript
    • this is regular javascript in this tag, so you can write functions and such too, not just pass variable names --- but don't want to clutter it up
    • <%= %> - the value inside the tag will be rendered to the page and added to the html
    • <% %> - use for logic/control flow stuff when we don't want to display anything on the page
  • to send info to the EJS template we use : res.render(fileName.ejs, {templateVariableName : appJsVariableName})
  • to stop from having to type .ejs at the end of every filename we can tell just tell express they are all ejs files
    • use app.set('view engine', 'ejs');
  • there of lots of other templating languages and systems, but their core functionality is all the same

Styles

  • stylesheets go in public directory
  • express doesn't know to serve the public directory automatically like it does the views directory
  • in app.js we need to add app.use(express.static('public'));

Partials

  • basically templates that we can include in other templates
  • put each partial in its own file
  • put the files in partials directory within the views directory
  • include them with <%- include('partialFileName') %>
  • in the header partial, in the link tag, put a / before the file name app.css so the right source directory is searched
  • can have partials for anything we need on multiple pages, not just headers and footers --- nav bars, menus, etc

Copyright © 2022