Разработка движков шаблонов для Express
Используйте метод app.engine(ext, callback) для создания собственного движка шаблонов. ext относится к расширению файла, а callback — это функция движка шаблонов, которая принимает следующие параметры: расположение файла, объект опций и обратный вызов.
Следующий код является примером реализации очень простого движка шаблонов для рендеринга файлов .ntl.
const fs = require('fs') // this engine requires the fs module
app.engine('ntl', (filePath, options, callback) => { // define the template engine
fs.readFile(filePath, (err, content) => {
if (err) return callback(err)
// this is an extremely simple template engine
const rendered = content.toString()
.replace('#title#', `<title>${options.title}</title>`)
.replace('#message#', `<h1>${options.message}</h1>`)
return callback(null, rendered)
})
})
app.set('views', './views') // specify the views directory
app.set('view engine', 'ntl') // register the template engine
Теперь ваш приложение сможет рендерить файлы .ntl. Создайте файл с именем index.ntl в каталоге views со следующим содержимым.
#title# #message#
Затем создайте следующий маршрут в вашем приложении.
app.get('/', (req, res) => {
res.render('index', { title: 'Hey', message: 'Hello there!' })
})
При запросе на главную страницу, index.ntl будет рендериться как HTML.
© 2017 StrongLoop, IBM, and other expressjs.com contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v3.0.
https://expressjs.com/en/advanced/developing-template-engines.html