mde / ejs

Embedded JavaScript templates -- http://ejs.co
Apache License 2.0
7.71k stars 846 forks source link

Include partial inside of another partial #765

Closed gdk16 closed 1 month ago

gdk16 commented 1 month ago

Hello, I wasn't sure where to ask this issue I'm having at, so I decided to do it here.

Say I had this in a partial file like partials/base.ejs, where it includes the base parts for all my pages, like including css/js, navbar, etc.:

<html>
<head>
other code here
</head>
<body>
other code here
<div class="container">

</div>
</body>
</html>

Is there a way to use that partial as a base wrapper around another partial file so that I don't have to do something like:

<%- include('partials/base1.ejs %>
<!-- inside of container div -->
<h1>test</h2>
<% - include('partials/base2.ejs %>

where the base1.ejs would be all the code required before, and the base2.ejs would be all the code required after, like closing tags.

Is EJS a correct method to doing this, or should I be doing it a different way or is this possible at all? Thanks!

gdk16 commented 1 month ago

I just thought of this, and I'm not sure if it's valid, but:

<!DOCTYPE html>
<html>

<head>
    <!-- header nonsense -->
    <link rel="stylesheet" href="./css/<%= file %>.css" />
</head>

<body>
    <!-- base content goes here -->
    <div class="content">
        <%- content %>
    </div>
    <!-- some scripts -->
</body>

</html>

Backend:

...
routes.forEach((obj) => {
    app.get(obj.path, (_, res) => {
        res.render("base", {
            "content": fs.readFileSync(`./views/partials/${obj.file}.ejs`),
            "file": obj.file,
        });
    });
});
...

Most of my non-static routes are just retrieving HTML pages but I like it to look extremely organized. Let me know if I can improve this and how! Thanks

mde commented 1 month ago

Yes, you can include include() calls inside of templates that already have include() calls. That is the correct way to structure things if you have lots of boilerplate.