2

Suppose i have some scripts which are common for all the pages and some scripts which are required only on specific page what is the efficient way to implement this using nunjucks as template engine and express 4 as the framework on backend.

--- site
 --- public
  |___js
    |___ script.js (for all pages)
    |___ home.js (only required on home page)
    |___ contact.js (contact page)
    |___ search.js  (on search page)

I have tried to use express locals for passing in the page title and sending the array of common scripts + home.js but on rendering script tags theres another call made to express middleware for route (*) which resets the scripts to common as no page title is passed to the function.

1 Answer 1

1

If contact, search and other is a different html template then you can use block-override

// index.njk
<html>
<head> 
    <script src = "script.js"></script>
    {% block js %}{% endblock %}
</head>

// search.njk
{% extends 'index.njk' %}

{% block js %}
    <script src = "search.js"></script>
{% endblock %}

// js
app.get('/search', function(req, res, next){
    res.render('search.njk', {...});
})

Another way likes yours

// Middleware
function(req, res, next) {
    res.locals.scripts = ['script.js'];
    next();
}

// router
app.get('/search', function(req, res, next) {
    res.render(#template-name, {
        scripts: res.locals.scripts.concat('search.js')
    })
})

// index.njk
<html>
<head> 
    {% for script in scripts %}
    <script src = "{{script}}"></script>
    {% endfor %}
</head>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.