Another way towards isomorphism: client-side Nunjucks and and server side Jinja2

tl;dr We love some of the ideals of the isomorphic pattern, we just weren’t ready to go all in with Node and React, so we’re trying another way.

We’re now at least six years into the concept of isomorphic web development which share significant amounts of code between client-side and server-side. Obviously as a small team who love code reuse, the idea of sharing parts of the application code between front and backend is highly appealing to us at Bimble.

On the other hand we’re also not ready to jump into developing an application using a conventional isomorphic stack (Node/React etc). We’re far more at home with developing in Python and Flask with Jinja2 as a templating library. We’re absolutely not against Node and React or any of the other conventional parts of the isomorphic stack, but they’re not where our experience and skillsets naturally lie.

We’re also very much in the progressive enhancement, progressive rendering and progressive web app camp. I think this tweet from Paul Lewis sums things up perfectly.

We’ll want to send the HTML for first paint from the back end where we can, sending enough data to the client to complete a view. We may then want to augment this with data from our API and with client side templates. Obviously the moment we start thinking like this alarm bells go off with the thought of maintaining two sets of templates and the consequences of that such as duplicated effort and risk of UI inconsistency if the templates start to diverge for any reason.

We think we’ve found a potential solution for this, and because we believe in the GDS statement of “Make things 0pen: it makes things better” we thought we’d share. Nunjucks, created by Mozilla, is a JavaScript templating language which is heavily inspired by Jinja2. The majority of documentation is around using it server side with Node, but there is also a way you can use it client side where you pre-compile the templates using a Gulp task and use the very stripped down nunjucks-slim library in the browser. At 30kb it’s not as small as the 3kb of Preact, but it’s still pretty lightweight.

We’ve created a lightweight example to share our learning. Templates are referenced on the client side by the filename of the original Jinja2 template which actually makes tracing back to the original template easy and are invoked in a simple “nunjucks.render” call with the template reference and a dictionary of variables to be use in the template as the two arguments which is very similar to the “render_template” method in Flask. In our example the form can either be submitted with or without JavaScript. Without JavaScript the templates are invoked in a POST method in Flask. With JavaScript the templates are invoked client side with data returned by an API method.