Write clean and maintainable HTML code

|  Posted: January 27, 2020  |  Categories: Angular TechMeet360

We all have come through posts where people show off how to write cool stuff in the backend/server-side in languages like C#, nodeJs, java, javascript, etc. Today let us understand, it is also absolutely necessary to structure your front-end side clean and nice as well. So let’s get started.

Recently I came across a certain area in application example navigation bar, where there is a lot of sub-menus which need to be shown. An example would be like this

side-bar

If you look at the menu items from a front end or developer’s brain, it can be summarized as 

  • It is just a list of menu items
  • Has a name
  • Has an icon
  • It should redirect to subpage or URL
  • Displayed in an unordered list

So usually we would write HTML template to render the above image like this

old-html

So the li is repeated multiple times with an appropriate class and the name of the item. Let’s say during development we keep adding menu items. But in a long span, it becomes redundant and there will be 500 lines just for the sidebar. So how do we improve it?

Explore more on Serverless Notes

 The Engineering brain kicks in

The for loop that you studied in your university must be kicking in your head. You can iterate over a list of items, because since its sidebar and the menu’s will be known values, so you can always iterate and display them.

We are in the 21st century. Any javascript framework that you use, be it Angular / Vue / React, it has a way to iterate objects and render them in the HTML template.  So i re-wrote the above code like this. This below snippet is from for Angular applications.

new-template

So this looks much cleaner, and you will never have to touch the HTML to add new menu item. So how’d you do it? Open your respective HTML helper, in the angular side it is typescript, so if you react it must be javascript. All you need to do is create an array like this.

javascript

Conclusion

I hope this helps you in writing much more awesome HTML templates. You might think oh wait, even my application has a lot of menu and submenu. Let me conclude this by saying a famous quote from Robert Baden-Powell

Try and leave this world a little better than you found it, and when your turn comes to die, you can die happy in feeling that at any rate, you have not wasted your time but have done your best.

Author: Hariharan subramanian

Software Engineer. c# and Azure Enthusiast.Passionate about Biking and Travelling.

Get notified about any future events

Interested in learning more about TechMeet360 or knowing about any future events? Sign up below to get notified.

Back to Top