Finish variables

This commit is contained in:
conzer 2024-12-05 23:53:34 -05:00
parent 89fff8112f
commit 1f98b9c421
7 changed files with 164 additions and 88 deletions

View file

@ -3,12 +3,14 @@ package compiler
import (
"fmt"
"os"
"strings"
"hylia/parser"
)
// THE HYLIA COMPILER
func Compile(elements []parser.Element, outputFile string) error {
func Compile(elements []parser.Element, variables map[string]string, outputFile string) error {
var head string
var body string
@ -42,27 +44,11 @@ func Compile(elements []parser.Element, outputFile string) error {
return fmt.Errorf("Failed to write to the output file: %w", err)
}
if head != "" {
_, err = file.WriteString("<head>\n" + head + "</head>\n")
if err != nil {
return fmt.Errorf(errmsg, err)
}
}
if body != "" {
_, err = file.WriteString("<body>\n" + body + "</body>\n")
if err != nil {
return fmt.Errorf(errmsg, err)
}
err = writeElements(elements, file, variables)
if err != nil {
return fmt.Errorf(errmsg, err)
}
if other != "" {
_, err = file.WriteString(other)
if err != nil {
return fmt.Errorf(errmsg, err)
}
}
// Close the HTML structs
_, err = file.WriteString("</html>\n")
if err != nil {
@ -71,4 +57,66 @@ func Compile(elements []parser.Element, outputFile string) error {
return nil
}
func writeElements(elements []parser.Element, file *os.File, variables map[string]string) error {
for _, element := range elements {
if element.Name == "head" {
_, err := file.WriteString(fmt.Sprintf("<head>\n"))
if err != nil {
return fmt.Errorf("Failed to write element %s: %w", element.Name, err)
}
}
if element.Name == "body" {
_, err := file.WriteString(fmt.Sprintf("<body>\n"))
if err != nil {
return fmt.Errorf("Failed to write element %s: %w", element.Name, err)
}
}
content := replaceVariables(element.Content, variables)
if strings.TrimSpace(content) != "" {
_, err := file.WriteString(strings.TrimSpace(content) + "\n")
if err != nil {
return err
}
}
// recursively process nested elements
if element.NestedElements != nil && len(element.NestedElements) > 0 {
err := writeElements(element.NestedElements, file, variables)
if err != nil {
return err
}
}
if element.Name == "head" {
_, err := file.WriteString(fmt.Sprintf("</head>\n"))
if err != nil {
return fmt.Errorf("Failed to write element %s: %w", element.Name, err)
}
}
if element.Name == "body" {
_, err := file.WriteString(fmt.Sprintf("</body>\n"))
if err != nil {
return fmt.Errorf("Failed to write element %s: %w", element.Name, err)
}
}
}
return nil
}
func replaceVariables(content string, variables map[string]string) string {
for key, value := range variables {
placeholder := fmt.Sprintf("{{%s}}", key)
content = strings.ReplaceAll(content, placeholder, value)
}
return content
}