3.8 KiB
Executable File
Views
In Strapi, views are markup templates that are compiled on the server into HTML pages. In most cases, views are used as the response to an incoming HTTP request.
!!! important By default, Strapi doesn't use views. The philosophy of the framework is to separate the reusable backend application logic from the front-end.
Configuration
Configuration:
- Key:
views
- Environment: all
- Location:
./config/general.json
- Type:
object
Example:
{
"views": {
"map": {
"html": "lodash",
"hbs": "handlebars"
},
"default": "html",
"cache": false
}
}
Options:
map
: Object mapping extension names to engine names.default
: Default extension name to use when missing.cache
: Whentrue
compiled template functions will be cached in-memory, this prevents subsequent disk I/O, as well as the additional compilation step that most template engines peform. By default this is enabled when theNODE_ENV
environment variable is anything butdevelopment
, such asstage
orproduction
.
Notes:
- Set to
false
to disable views support. - Views are defined in your application's
./views
directory. - You still need to install the engines you wish to use, by adding them to your
package.json
dependencies.
Usage
Simply use this.render
instead of this.body
to render a view.
You don't need to specify the view extension if you use the default one sets in config.
Using the config we wrote above with lodash
for .html
files and use the html
extension by default, this example will render ./views/user.html
with Lodash as template engine.
yield this.render('user', {
firstname: 'John',
lastname: 'Doe'
});
<html>
<head>...</head>
<body>
<p>Firstname: <% firstname %><br>Lastname: <% lastname %></p>
</body>
</html>
Here is the same example with the jade
extension, not used by default:
yield this.render('user.jade', {
firstname: 'John',
lastname: 'Doe'
});
Supported template engines
To use a view engine, you should use npm to install it in your project and set the map
object in strapi.config.views
.
Strapi supports all of those view engines: