In the world of web development, templating engines play a crucial role in separating presentation logic from business logic. One such popular templating engine is Pug (formerly known as Jade), which offers a clean and concise syntax for writing HTML templates. This tutorial will introduce you to Pug's basic concepts, syntax, and how it can be integrated into your web projects.
Pug is a high-performance template engine that compiles into optimized JavaScript code. It allows developers to write HTML in a more readable and maintainable way by using indentation-based syntax instead of traditional HTML tags. This approach reduces the amount of boilerplate code and makes templates easier to manage, especially for larger projects.
Let's dive into some practical examples to understand how Pug works.
Here is a simple example of how to write HTML using Pug:
1doctype html2html(lang="en")3head4title My Page5body6h1 Hello, World!
When compiled, this Pug code will produce the following HTML:
<!DOCTYPE html> <html lang="en"> <head> <title>My Page</title> </head> <body> <h1>Hello, World!</h1> </body> </html>
You can add attributes to elements using parentheses or curly braces. Here's how you can define classes and other attributes:
1doctype html2html(lang="en")3head4title My Page5body(class="container")6h1(class="title") Hello, World!
This will compile to:
<!DOCTYPE html> <html lang="en"> <head> <title>My Page</title> </head> <body class="container"> <h1 class="title">Hello, World!</h1> </body> </html>
Mixins are reusable components that can be defined and used throughout your templates. Here's an example of how to create and use a mixin:
1doctype html2html(lang="en")3head4title My Page5body(class="container")6mixin button(text)7button(type="button")= text89+button('Click Me')
This will compile to:
<!DOCTYPE html> <html lang="en"> <head> <title>My Page</title> </head> <body class="container"> <button type="button">Click Me</button> </body> </html>
Pug supports template inheritance, which is useful for creating consistent layouts. Here's an example:
layout.pug
1doctype html2html(lang="en")3head4title My Page5body(class="container")6block content
index.pug
1extends layout23block content4h1 Hello, World!5p This is a paragraph.
When index.pug is compiled, it will extend the layout.pug and replace the content block:
<!DOCTYPE html> <html lang="en"> <head> <title>My Page</title> </head> <body class="container"> <h1>Hello, World!</h1> <p>This is a paragraph.</p> </body> </html>
Now that you have a good understanding of Pug and its syntax, you might want to explore other templating engines like Handlebars Templates. Handlebars offers a different approach with its own set of features and capabilities, which can be useful depending on your project requirements.
Feel free to experiment with Pug in your next web development project and see how it can simplify your HTML templates.