-
Notifications
You must be signed in to change notification settings - Fork 861
Open
Description
Currently ejs doesn't have any block/template/extend features.
existing solutions:
https://github.com/seqs/ejs-blocks
neat javascript grammar, however it only support raw strings as block content.
tj/ejs#142 https://github.com/User4martin/ejs/blob/plugin-snippets/docs/plugin-snippet.md
they invents several preprocessor directives like
<%block header%>,<%/block header%><%+ template%>,<%* snippet name %>,<%* /snippet %>, thus not very easy to learn, this is against ejs's design goals.
this approach:
page implementation (home.ejs):
<!-- define block contents by functions, it should be able to access the same locals data & context -->
<% var head = () => { %>
<%- include('./include.css') %>
<title>Hello EJS Template</title>
<% } -%>
<% var body = () => { %>
<div>
you have an message: <%= message.toLowerCase() %>
</div>
<% } -%>
<!-- a single "include" finally, and its contents are passed by locals -->
<%- include('./layout', {body, head}) %>template/layout declaration (layout.ejs):
<!-- NOTE: template/layout can be nested -->
<html>
<head>
<% if (!head) { %>
<title>default title</title>
<% } else { %>
<!-- NOTE: this is the only one thing changed for ejs users, ejs "include" function now accept function as its first argument -->
<%- include(head) %>
<% } %>
</head>
<body>
<h1>This is a layout</h1>
<% if (!body) { %>
<small>default content</small>
<% } else { %>
<!-- same above -->
<%- include(body) %>
<% } %>
</body>
</html>advantages
- pure javascript gramma, with ES6 arrow function, the code looks nice too
- it breaks nothing
- like the original "include", it can be nested
- functions can have its parameters, so include can handle function-local variables as well as context variables, example: block/template/extend support for ejs #252 (comment)
woneob, larrybahr, pushingit, huzunjie, ozywuli and 8 more
Metadata
Metadata
Assignees
Labels
No labels