Converting HTML to PUG means taking an HTML file and rewriting it in PUG syntax, which simplifies the code by removing redundant tags, using indentation to denote structure, and enabling reusable components through features like mixins.
How to Convert HTML to PUG:
To convert HTML to PUG, you manually rewrite the HTML code in PUG syntax. Here's how HTML elements are typically transformed into PUG:
Example 1: Simple HTML to PUG Conversion
HTML Code:
html
<!DOCTYPE html>
<html>
<head>
<title>HTML to PUG Example</title>
</head>
<body>
<h1>Hello, World!</h1>
<p>This is an example of HTML to PUG conversion.</p>
</body>
</html>
PUG Code:
pug
doctype html
html
head
title HTML to PUG Example
body
h1 Hello, World!
p This is an example of HTML to PUG conversion.
Key Differences Between HTML and PUG:
No Closing Tags: PUG does not require closing tags for most elements. For example, the <h1> tag doesn't need a </h1>, and the <body> tag doesn't need </body>.
Indentation: The structure of the document is determined by indentation, rather than opening and closing tags.
Attributes: In PUG, you define attributes within parentheses next to the element.
HTML: <a href="https://example.com">Click here</a>
PUG: a(href="https://example.com") Click here
Example 2: HTML with Nested Elements
HTML Code:
html
<div class="container">
<ul>
<li><a href="#">Item 1</a></li>
<li><a href="#">Item 2</a></li>
<li><a href="#">Item 3</a></li>
</ul>
</div>
PUG Code:
pug
.container
ul
li
a(href="#") Item 1
li
a(href="#") Item 2
li
a(href="#") Item 3
Important Notes When Converting:
Attributes: In HTML, attributes are within tags like class="...". In PUG, they go inside parentheses: class="..." becomes (class="...").
Self-Closing Tags: For elements like <img>, <br>, and <input>, in HTML, they are self-closing. In PUG, they are written without a closing tag and a space before the closing / (e.g., img(src="image.jpg")).
Tools for Converting HTML to PUG:
There are also some online tools and npm packages that can help you automatically convert HTML to PUG, such as:
PUG Online Converter
html2pug npm package: You can install this package globally and use it to convert HTML files to PUG in the command line.
bash
npm install html2pug -g
html2pug yourfile.html
Summary:
Converting HTML to PUG helps reduce repetitive code, improves readability, and makes it easier to work with templating engines. You remove closing tags, use indentation to represent the document structure, and use PUG's built-in features for more dynamic content.