Search code examples
javascriptnunjucks

Problem using Nunjucks functionalities in "index.html"


I'm trying to use Nunjucks (client-side) as the templating component of my project. I'm using xampp, apache for the server.

The problem is that when i put "nunjucks code" inside the index.html, it doesn't compile it. If i put "{% include "sidebar.html" %}" it just renders that in the DOM.

I'm being able to use the render method AFTER the DOM is loaded, and in my templates, everything works.

index.html (DOESN'T WORK):

<!DOCTYPE html>
  <html lang="en">
    <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <!-- Meta, title, CSS, favicons, etc. -->
      ...
     <body>
        ...
        {% include "sidebar.html" %} // This gets rendered literally
        ...
     </body>
     ...

So, basically i want to know if it's possible to use nunjucks functionalities in the first page that is served by apache (in this case, index.html).

Thanks in advance.


Solution

  • Try it

    // index.html
    <html lang="en">
      <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <script src = "/js/vendors/nunjucks.min.js"></script>
      <script>
      window.addEventListener('load', function () {
        nunjucks.render('index.njk', {some-data}, (err, html) => body.innerHTML = err && err.message || html);
      });
      </script>
      <body>
      <!-- Empty body -->
      </body>
    </html>
    
    // index.njk
    {% include "sidebar.njk" %}
    ...