Beginner Questions about Partial

I have a simple page with a title, menu, content and footer. I need to split them into separate files. After reading the express documentation, I (created 4 templates and) wrote something like this:

app.get('/', function(req, res) {
    var response = [null, null, null, null]
    , everyNotNull = function(elem) {
        return (elem !== null);
    }, sendResponse = function(type, str) {
        switch (type) {
            case 'head' : response[0] = str; break;
            case 'menu' : response[1] = str; break;
            case 'content' : response[2] = str; break;
            case 'footer' : response[3] = str; break;
        }

        if (response.every(everyNotNull)) {
            res.send(response.join(''));
        }
    };

    res.partial('head', {'title' : 'page title'}, function(err, str) {
        sendResponse('head', str);
    });

    res.partial('menu', {'active' : '/'}, function(err, str) {
        sendResponse('menu', str);
    });

    res.partial('index', {'title' : 'Home'}, function(err, str) {
        sendResponse('content', str);
    });

    res.partial('footer', {'nowdate' : (new Date()).getFullYear()}, function(err, str) {
        sendResponse('footer', str);
    });
});

Although this works, it seems to me a little dirty. Is there a better way to use partial patterns?

+5
source share
1 answer

You were right, suspecting that something was missing, you are doing unnecessary work there.

Express will stitch the templates together for you, just call res.render () and the name of the view you want to call. Layout and partial parts should be automatically inserted.

, . EJS (Jade, ..):

./Library/app.js

app.get('/', function(req, res) {
    var model = {
        layout:'customLayout', // defaults to layout.(ejs|jade|whatever)
        locals:{
            foo:'bar'
        }
    };
    res.render('index',model);
});

.//layout.ejs

<html>
    <head><%- partial('partials/head') %></head>
    <body>
<%- partial('partials/menu') %>
<%- body %>
<%- partial('partials/footer') %>
    </body>
</html>

.//index.ejs

<h1>Index page</h1>

.///menu.ejs

<div><a href='... </div>

.///head.ejs

<script>...</script>
etc.
+5

All Articles