Templates - Server-Side Rendering
You are reading the documentation for version 2 of FoalTS. Instructions for upgrading to this version are available here. The old documentation can be found here.
Regular Web Applications rely on templates to dynamically generate HTML pages on the server. These templates are text files that contain static content as well as a special syntax describing how the data should be inserted dynamically. During an HTTP request, the application loads and renders the template using the given contextual data and sends back the page to the client.
This technique is known as Server-Side Rendering (or SSR).
Here is an example of what a template might look like:
#
Rendering TemplatesFoalTS provides a minimalist template engine to render templates. This engine replaces all the occurrences of {{ myVariableName }}
with the given values.
Here is an example showing how to use it:
templates/index.html
src/app/app.controller.ts
Output (GET /)
#
Using Another Template EngineExternal template engines, such as EJS or pug, are also supported and can be configured for the current project using the configuration key settings.templateEngine
.
Here is an example showing how to configure config/default.json
(or config/default.yml
) with twig, a JS implementation of the Twig PHP templating language.
- YAML
- JSON
- JS
Then the render
function uses this engine under the hood to render the templates.
Note: Only Express compatible template engines are supported (which represents the large majority of those available on npm).
templates/index.html (Twig example)
src/app/app.controller.ts (Twig example)
Output (GET /) (Twig example)
#
Templates LocationBy default, the render
function loads templates from the project root directory.
But the path can also be relative to the controller file. The render
function accepts a third parameter dirname
for this purpose.