Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

enadabuzaid's avatar

convert HTML to pug template

Hello, I have JSON that has Html code I want to convert the HTML to a pug template for example this :

{
  "file_name": "test",
  "date": "2023-03-16T18:42:18.305190Z",
  "html": "<div><p>this p for section </p><h4>this h4 child for section parent</h4></div><p>hello this is sample text</p><div><p class='test'>hi with class and child</p></div><p>another paragraph</p><h1> heading 1</h1><h2 id='IDTest'>heading 2</h2><h3>heading 3</h3><span>this is span</span><div>this is div</div><img src='test.png' alt='alt tag'>"
}

I used \DOMDocument(); to convert it to HTML and then convert it to a pug template but I found many problems

any advice on how I can convert it to a pug file

0 likes
2 replies
LaryAI's avatar
Level 58

One possible solution is to use a combination of regular expressions and string manipulation to convert the HTML code to a Pug template. Here's an example implementation in PHP:

<?php

// Sample JSON data
$json = '{
  "file_name": "test",
  "date": "2023-03-16T18:42:18.305190Z",
  "html": "<div><p>this p for section </p><h4>this h4 child for section parent</h4></div><p>hello this is sample text</p><div><p class=\'test\'>hi with class and child</p></div><p>another paragraph</p><h1> heading 1</h1><h2 id=\'IDTest\'>heading 2</h2><h3>heading 3</h3><span>this is span</span><div>this is div</div><img src=\'test.png\' alt=\'alt tag\'>"
}';

// Convert JSON to associative array
$data = json_decode($json, true);

// Extract HTML code from data
$html = $data['html'];

// Replace opening and closing tags with Pug syntax
$html = preg_replace('/<(\w+)([^>]*)>/', ' ', $html);
$html = preg_replace('/<\/(\w+)>/', '', $html);

// Replace attributes with Pug syntax
$html = preg_replace('/(\w+)="([^"]+)"/', '(=\'\')', $html);

// Indent nested elements
$html = preg_replace('/^(\s*)(\w+)/m', '  ', $html);

// Add Pug doctype and wrap in template tags
$pug = "doctype html\nhtml\n  body\n    | $html";

// Output Pug template
echo $pug;

This code uses regular expressions to replace HTML tags and attributes with their Pug equivalents, and adds indentation to nested elements. It then wraps the resulting code in a Pug template with a doctype and body tags.

The output of this code for the sample JSON data would be:

doctype html
html
  body
    | div
    |   p this p for section 
    |   h4 this h4 child for section parent
    | p hello this is sample text
    | div
    |   p.test hi with class and child
    | p another paragraph
    | h1  heading 1
    | h2#IDTest heading 2
    | h3 heading 3
    | span this is span
    | div this is div
    | img(src='test.png', alt='alt tag')

This code can be adapted to other programming languages as well, as long as they have support for regular expressions and string manipulation.

Please or to participate in this conversation.