Templating HTML in Frontend Development

Building static HTML’s it’s fun (yes, it is) but it can become a boring copy & paste task sometimes. That’s why today I want to introduce a template engine for HTML.

What do I want to achieve?

  • Write less HTML.
  • Faster HTML maintenance and bug fixing.
  • Better experience when working with 2 or more developers on HTML’s.
  • Faster prototyping, faster delivery.

jinja template engine

jinja

There are many template engines out there. The one I chose, based on who uses it, is Jinja.

Since we’re not going to use the full potential of the template engine I don’t think it matters much which one you pick, as long as it has a grunt plugin.

Jinja2 is a full featured template engine for Python. It has full unicode support, an optional integrated sandboxed execution environment, widely used and BSD licensed.

More information and documentation on its website: http://jinja.pocoo.org/

Includes

The feature that got me into using this is the include. You already know how this work.

It’s a must in order to follow the DRY rule: don’t repeat yourself.

{% include "includes/_head.html" %}

... specific page content ...

{% include "includes/_footer.html" %}

Before using templates if I had to change an item on the menu component, a class or a tag that was used in all pages, well… I had to do it manually for all pages. Maybe for some cases I could do a “find & replace”. But in any case, still a hassle.
Now I just edit the template file and all the pages are recompiled instantly with the new change.

Variables

We can also set variables:

{% set pageTitle = "Home" -%}

Then use it on our templates as so:

<title>{{ pageTitle }}</title>

I use this mostly for the page meta title. I set the variable before including the _head.html template so that it will inherit the value. It allows me to have just 1 file for the head HTML but at the same time customized for each page.

Loops

A grid view of images? A list of products?

For all those cases we can use a loop. This will allow us to just write the item/component once. The maintenance will be really easy afterwards.
Imagine using the old way and having a component repeated 20 times in the same page.

You need to change a class? Need to add new markup to the component?

If you’re using a loop, just change it once.

{% for _ in range(0, 10) -%}
 <div class="card">

 <img src="" alt=""> 
 
 <a href="#">
 <h1>Title Link</h1>
 </a>
 
 <p>
 Some Text
 </p>
 
 <a href="#">Button</a>

 </div>
 <!-- .card -->
{% endfor -%}

With the code above we’ll repeat the card component 10 times. This is a real time saver when I have to modify the component in any way.

Loops with Arrays

Things can get very interesting. Say you want to create a menu or a component but with unique text for each item.

We can use the for statement and loop through an array

<ul>
 {% for item in [
   ["Title 1", "red"],
   ["Title 2", "blue"],
   ["Title 3", "green"],
   ["Title 4", "yellow"]
  ]
 -%}
   <li class="{{ item[1] }}">{{ item[0] }}</li>
  {% endfor -%}
 </ul>

It will be rendered in:

 <ul>
  <li class="red">Title 1</li>
  <li class="blue">Title 2</li>
  <li class="green">Title 3</li>
  <li class="yellow">Title 4</li>
</ul>

Although this is a very simple example the component we want to repeat could be very complex, markup wise.

Grunt

None of these awesomeness would make any sense if we weren’t able to build the HTML on each file save.

Using a grunt task we can watch over the source HTML files and compile them. It’s really fast so no development delay.

Check out grunt-jinja for more information.

Folder structure

Pretty straight forward:

  • /html/
  • /html-source/includes/_head.html
  • /html-source/includes/_footer.html
  • /html-source/homepage.html
  • /html-source/product.html
  • /html-source/login.html

It can be anything since you’re free customize the jinja grunt task to fit your project.

What does this mean for the Backend Developer?

Nothing. Nada. Nic. You will still have a folder called html for the compiled files.

Just remember, if you need to change the static HTML’s you will have to update the html–source folder and run the grunt task. Otherwise bad things will happen.

Conclusion

Additionally to all this, since we’re splitting up the files we can easily have multiple developers working on HTML’s without stepping in each other toes.
One can work on the _head.html file, while the other on the homepage.html file. Both will be able to commit their code and do changes without having to merge. Pretty sweet.

I believe using this templating engine will boost your productivity while the impact on your workflow will be minimal. I’ve already used it on a real project and it has greatly improved my delivery and bug fixing times.

Your thoughts?

Save yourself some time: Automating tasks in Frontend Development

Working on a frontend project you probably have dealt with CSS and JavaScript files. How do you handle those? Do you minimize them? Do you combine them?

I’m sure you’re aware of the benefits of minifying assets. You can save a lot of Kb’s from your CSS and JavaScript files. Nowadays performance matters, it really does. With more and more mobile users every day, your site should be lightweight.

How do we minify and/or combine assets before moving your site to production?

First of all, here’s a thought about folder structure for your project:

/dist
/dist/css
/dist/javascript
/source
/source/css
/source/javascript

I’d recommend using a folder structure similar to this one. Grunt does not force you to any specific folder structure, you’ll have the freedom to set the output folders on each task.

You’ll be doing all your work in the source folder. Your files will be commented, uncompressed and separated into components. It’s a good practice to breakdown your CSS into different files, it will help you and your team keep the code organized. Great for collaboration.

What’s with the dist folder?

The dist folder will eventually have all the processed files, perhaps a single CSS file (merged from 10 separate CSS components).

Bear in mind though:

Combining all CSS/JavaScript into 1 file is not a synonym for optimal performance.

Grunt-JavaScript

Grunt.js to the rescue

Let me quote what’s on the Grunt website:

In one word: automation. The less work you have to do when performing repetitive tasks like minification, compilation, unit testing, linting, etc, the easier your job becomes.

Doing everything I’ve been chattering about is possible with Grunt. Why’s so great?

  • Speed: all the tasks will be done for you, either every time you edit a file or whenever you run the terminal command.
  • Working with a team: the whole team will have the same file structure, you’ll share the configuration file so everybody will generate the same production files.
  • It’s what the cool kids are using.

How does it work? I think it’s best for you to take a few minutes and jump to the Get Started tutorial from their site.

Done reading? Cool, let’s continue.

Remember the dist folder I mentioned earlier? On most of the Grunt tasks you’ll set up is an output folder.

/* Grunt Config File */

concat: {
 css_main: {
 src: ['source/css/components/*.css'],
 dest: 'dist/css/project-main.css'
 },
}

NOTE: the concat task is part of the Concat Grunt Plugin. You must install it and configure it before using the concat task.

You’ll set it to this new dist folder so all your processed, compressed code will be located there (in the case above we’re merging all our files into one and saving it as project-main.css ).
When it comes to production we don’t want to upload our source CSS/JS files.

Watch for file changes.

That’s probably my favourite feature of all. By using the Grunt Watch Plugin you can simply run the grunt task on your terminal and watch over the changed files (please notice you’ll need some extra configuration in your Grunt config file before actually making this work, refer to the plugin’s site):

grunt

This will keep an open task in your terminal that will wait for any file change. Every Time you edit a SCSS or JavaScript file, Grunt will re-run. What’s great is that it will not run the whole thing.
Say all tasks (merge, compress, minify, move…) take up to 30 seconds. With the grunt watch it will just compile the affected files. Meaning it might only take 5 seconds.

I don’t like the Grunt logo, are there any alternatives?

Yes, check out Gulp.js

There’s plenty of blog posts out there breaking down a comparison side by side. It’s your job to decide what’s best for you and your team.

From what I’ve read both are more than capable of delivering your needs.

gulp grunt

Final thoughts

I know what you think, do I have to learn yet another tool?

I felt the same way the first time I read about Grunt.js At that time I was using a desktop application for compiling SASS, running JSLint, minifying… and that’s great, until there’s two developers working on the same project.

It can get complicated, some Grunt configuration files can easily have 300 lines. However, once you start reading and looking into it you’ll see it’s less painful than how it looks.

In my previous article I was trying to convince you to start coding your CSS using a CSS Preprocessor (SASS). With Grunt you can process all that files, merge them and move them to the dist folder without even thinking about it.

Did you know about Grunt? Are you already using it?