Như các bạn đã biết consolidate là 1 template engine được sài phổ biến bên nodeJS vì nó cho mình thao tác với hầu hết các template engine hiện tại, Thông tin thêm bạn có thể xem trên trang của nó
Hiện tại mình đang áp dụng consolidate để sử dụng Handlebars template engine kết hợp với expressJS. Cấu trúc mã như bên dưới:
import consolidate from 'consolidate'; // More imports app.use('/static', express.static(path.join(__dirname, 'assets'))) // assign the handlebars engine to .html files app.engine('html', consolidate.handlebars); // set .html as the default extension app.set('view engine', 'html' ); app.set('views', path.join(__dirname, './views'));
Mình có một hàm sử lý để generate template theo tên template, ví dụ:
module.exports = { renderTemplate( templateName = '', context = {}, options = {} ) { return consolidate.handlebars( path.join(__dirname , '../views', `${templateName}.html`), {...context, ...options }); } }
Hàm renderTemplate là một hàm tiện ích, bạn viết ở đâu đó rồi sài lại.
Và ở controller NodeJS mình sẽ sử dụng:
const quotes = await renderTemplate('quotes', { ...req.body}, { helpers: { truongluu: () => { return 'truongluu' } } });
Ở đoạn mã phía trên mình có tạo 1 helpers là truongluu xuất ra chuỗi ‘truongluu’, và trong template của bạn bạn đã sài được cái helper này rồi nhé
{{#each quotes}} <tr> <td class="text-center">1</td> <td class="text-center"> <img width="50" src="http://luuxuantruong.info/{{image}}" alt="" /> </td> <td>{{name}}</td> <td class="specifies-list"> {{shortContent}} </td> <td class="text-center">{{quantity}}</td> <td class="text-right">{{regularPrice}} {{truongluu}}</td> <td></td> </tr> {{/each}}