Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Block inheritance in EJS templates

Tags:

express

ejs

base.ejs:

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>My Diary</title>
    <link rel="stylesheet" href="stylesheets/bootstrap.min.css">
    <script src="javascripts/jquery.js" ></script>
    <script src="javascripts/bootstrap.min.js"></script>

</head>
<body>
<script type="text/javascript">

$(document).ready(function(){

});




</script>

</body>

index.ejs:

<div class="container">
<!-- Button trigger modal -->
<h1>Welcome to Your Diary</h1>
<div>


<span class="label label-default">What would you like to do? </span>&nbsp;
<span class="label label-primary">Here are your Categories:</span>&nbsp;


</div>
</div>

I want block inheritance

like image 277
sly_Chandan Avatar asked Jan 22 '17 20:01

sly_Chandan


People also ask

What is better than EJS?

Handlebars. js, React, Pug, JSX, and Mustache are the most popular alternatives and competitors to EJS.


2 Answers

EJS does not specifically support blocks, but layouts can be implemented by including headers and footers, like so:

<%- include('header') -%>
<h1>
  Title
</h1>
<p>
  My page
</p>
<%- include('footer') -%>

https://github.com/mde/ejs#layouts

You could split base.ejs into two files, header and footer, like this:

header.ejs

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>My Diary</title>
    <link rel="stylesheet" href="stylesheets/bootstrap.min.css">
    <script src="javascripts/jquery.js" ></script>
    <script src="javascripts/bootstrap.min.js"></script>

</head>
<body>

footer.ejs

<script type="text/javascript">

$(document).ready(function(){

});
</script>

</body>
</html>
like image 188
RyanZim Avatar answered Sep 23 '22 03:09

RyanZim


Someone has made EJS with block inheritance capability (https://github.com/mafintosh/pejs)

Straight from the documentation (Retrieved on January, 1st, 2018):

Using blocks it's easy to implement template inheritance. Just declare a base.html with some anchored blocks:

<body>
  Hello i am base
  <%{{ content }}%>
</body>

Then a child.html that renders base.html

<%{ './base.html' }%>
<%{ content %>
  i am inserted in base
<%} %>

To render the example just render child.html

pejs.render('./child.html', function(err, result) {
  console.log(result);
});

Looks pretty good. I'm going to try this on my own project.

like image 20
goFrendiAsgard Avatar answered Sep 23 '22 03:09

goFrendiAsgard