Express JS Express Template Engines 2 — Questions and Answers
Question 1: Which Express method is used to register a custom or third-party template engine?
- app.use()
- app.set()
- app.engine() (Correct answer)
- app.register()
Correct answer: app.engine()
app.engine(ext, callback) maps a file extension to a render function, allowing Express to use any compliant template engine.
Question 2: In EJS, which tag executes JavaScript code without rendering any output to the page?
- <%= %>
- <% %> (Correct answer)
- <%- %>
- <%_ %>
Correct answer: <% %>
<% %> is the scriptlet tag used for control flow (if/for/etc.) and executes code without writing output.
Question 3: Which Express setting changes the directory where template files are located?
- app.set('template dir', path)
- app.set('views', path) (Correct answer)
- app.use('views', path)
- app.set('view dir', path)
Correct answer: app.set('views', path)
app.set('views', path.join(__dirname, 'templates')) overrides the default views directory to any custom path.
Question 4: In EJS, which tag outputs raw unescaped HTML directly into the page?
- <%= %>
- <% %>
- <%- %> (Correct answer)
- <%+ %>
Correct answer: <%- %>
<%- %> outputs the value without HTML escaping, which is useful for rendering pre-sanitized HTML content.
Question 5: What is res.locals used for in Express template rendering?
- Storing variables available to templates for the current request only (Correct answer)
- Setting global app-level variables shared across all requests
- Caching previously rendered views
- Specifying which template engine to use for a single response
Correct answer: Storing variables available to templates for the current request only
res.locals is request-scoped; properties set on it are available to templates rendered during that request/response cycle only.
Question 6: In Handlebars (hbs), how do you output a variable named "title" in a template?
- <%= title %>
- #{ title }
- {{ title }} (Correct answer)
- ${title}
Correct answer: {{ title }}
Handlebars uses double curly braces {{ }} to output variables, with HTML escaping applied by default.
Question 7: In Pug templates, which syntax adds a CSS class to a div element?
- div[class=highlight]
- div.highlight (Correct answer)
- div#highlight
- div(id=highlight)
Correct answer: div.highlight
Pug uses CSS selector-like shorthand where a period followed by the class name (div.highlight) adds a class attribute.
Which Express method is used to register a custom or third-party template engine?