Skip to content

Commit

Permalink
Support multiple templates being used in single page
Browse files Browse the repository at this point in the history
  • Loading branch information
jellyterra committed May 24, 2024
1 parent 339dea1 commit 685185c
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 17 deletions.
22 changes: 22 additions & 0 deletions structure/job.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// Copyright 2024 Jelly Terra
// This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0
// that can be found in the LICENSE file and https://mozilla.org/MPL/2.0/.

package structure

const (
_ = iota

WAITING // Waiting for other content being generated.
FAILED // Error occurred.
DONE // Content generated successfully.
)

type Job struct {
Requires []string `toml:"requires"`
}

func (j *Job) Execute() error {
// TODO
return nil
}
45 changes: 28 additions & 17 deletions structure/page.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@
package structure

import (
"bytes"
. "github.com/webpagine/go-pagine/path"
"io"
"os"
"path/filepath"
"text/template"
)

Expand All @@ -18,33 +19,22 @@ type Page struct {
// RelativePath where the webpage attr file is.
RelativePath string

// TemplatePath the pages uses.
TemplatePath string `toml:"template"`
// Templates the pages uses.
Templates map[string]string `toml:"templates"`

// Contents sources: content.[string] = string
// It is designed for different part of content used in template.
//
// Example:
// content = "/content_000.md" => invoke "md" generator, assign the output to the key "content"
Contents map[string]string `toml:"content"`
Contents map[string]string `toml:"contents"`

// Customized data.
Data map[string]any `toml:"data"`
}

func (p *Page) Generate(root Path, w io.Writer) error {

// Parse Go template.
templateBody, err := os.ReadFile(root.AbsolutePathOf(p.TemplatePath))
if err != nil {
return err
}

t, err := template.New(p.RelativePath).Parse(string(templateBody))
if err != nil {
return err
}

var contentMap = map[string]any{}

for contentKey, contentRelativePath := range p.Contents {
Expand All @@ -63,8 +53,29 @@ func (p *Page) Generate(root Path, w io.Writer) error {
contentMap[dataKey] = dataValue
}

// Template
err = t.Execute(w, contentMap) // No
var templateMap = map[string]string{}

contentMap["templates"] = templateMap

for templateKey, templateRelativePath := range p.Templates {
path := root.AbsolutePathOf(templateRelativePath)

t, err := template.New(filepath.Base(path)).ParseFiles(path)
if err != nil {
return err
}

b := bytes.NewBuffer(nil)

err = t.Execute(b, contentMap)
if err != nil {
return err
}

templateMap[templateKey] = b.String()
}

_, err := w.Write([]byte(templateMap["main"]))
if err != nil {
return err
}
Expand Down

0 comments on commit 685185c

Please sign in to comment.