Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor template rendering #16

Draft
wants to merge 1 commit into
base: view-config
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 7 additions & 11 deletions cmd/build.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package cmd

import (
"errors"
"fmt"
"io/ioutil"
"os"
Expand All @@ -10,6 +9,7 @@ import (

"github.com/glaciers-in-archives/snowman/internal/config"
"github.com/glaciers-in-archives/snowman/internal/sparql"
"github.com/glaciers-in-archives/snowman/internal/templates"
"github.com/glaciers-in-archives/snowman/internal/utils"
"github.com/glaciers-in-archives/snowman/internal/views"
"github.com/knakk/rdf"
Expand Down Expand Up @@ -81,15 +81,6 @@ var buildCmd = &cobra.Command{
return utils.ErrorExit("Failed to parse snowman.yaml.", err)
}

templates, err := DiscoverTemplates()
if err != nil {
return utils.ErrorExit("Failed to find any template files.", err)
}

if len(templates) == 0 {
return errors.New("Failed to find any template files.")
}

queries, err := DiscoverQueries()
if err != nil {
return utils.ErrorExit("Failed to find any query files.", err)
Expand All @@ -100,7 +91,12 @@ var buildCmd = &cobra.Command{
return utils.ErrorExit("Failed to initiate SPARQL client.", err)
}

discoveredViews, err := views.DiscoverViews(templates, *repo, siteConfig)
templateCollection, err := templates.DiscoverAndParseTemplates(*repo, siteConfig)
if len(templateCollection.TemplatePaths) == 0 {
return utils.ErrorExit("Failed to find any template files.", err)
}

discoveredViews, err := views.DiscoverViews(*templateCollection)
if err != nil {
return utils.ErrorExit("Failed to discover views.", err)
}
Expand Down
72 changes: 72 additions & 0 deletions internal/templates/templates.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
package templates

import (
html_template "html/template"
"os"
"path/filepath"
"strings"
text_template "text/template"
"time"

"github.com/glaciers-in-archives/snowman/internal/config"
"github.com/glaciers-in-archives/snowman/internal/sparql"
)

type TemplateCollection struct {
Repository sparql.Repository
ParsedTextTemplates *text_template.Template
ParsedHTMLTemplates *html_template.Template
TemplatePaths []string
}

func DiscoverAndParseTemplates(repo sparql.Repository, siteConfig config.SiteConfig) (*TemplateCollection, error) {
var paths []string

var functionMap = map[string]interface{}{
"now": time.Now,
"split": strings.Split,
"replace": strings.Replace,
"lcase": strings.ToLower,
"ucase": strings.ToUpper,
"tcase": strings.ToTitle,

"query": repo.InlineQuery,
"config": siteConfig.Get,
"metadata": siteConfig.GetMetadata,
}

var textTemplateFuncMap = text_template.FuncMap(functionMap)
var htmlTemplateFuncMap = html_template.FuncMap(functionMap)

err := filepath.Walk("templates", func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
paths = append(paths, path)
}
return nil
})
if err != nil {
return nil, err
}

var parsedTextTemplate *text_template.Template
parsedTextTemplate, err = text_template.New("").Funcs(textTemplateFuncMap).ParseFiles(paths...)
if err != nil {
return nil, err
}

var parsedHTMLTemplate *html_template.Template
parsedHTMLTemplate, err = html_template.New("").Funcs(htmlTemplateFuncMap).ParseFiles(paths...)
if err != nil {
return nil, err
}

return &TemplateCollection{
Repository: repo,
ParsedTextTemplates: parsedTextTemplate,
ParsedHTMLTemplates: parsedHTMLTemplate,
TemplatePaths: paths,
}, nil
}
56 changes: 16 additions & 40 deletions internal/views/views.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,9 @@ import (
"os"
"path/filepath"
"regexp"
"strings"
text_template "text/template"
"time"

"github.com/glaciers-in-archives/snowman/internal/config"
"github.com/glaciers-in-archives/snowman/internal/sparql"
"github.com/glaciers-in-archives/snowman/internal/templates"
"gopkg.in/yaml.v2"
)

Expand All @@ -35,11 +32,19 @@ func (v *View) RenderPage(path string, data interface{}) error {
return err
}
if v.ViewConfig.Unsafe {
if err := v.TextTemplate.ExecuteTemplate(f, v.TemplateName, data); err != nil {
textTemplateCopy, err := v.TextTemplate.Clone()
if err != nil {
return err
}
if err := textTemplateCopy.ExecuteTemplate(f, v.TemplateName, data); err != nil {
return err
}
} else {
if err := v.HTMLTemplate.ExecuteTemplate(f, v.TemplateName, data); err != nil {
HTMLTemplateCopy, err := v.HTMLTemplate.Clone()
if err != nil {
return err
}
if err := HTMLTemplateCopy.ExecuteTemplate(f, v.TemplateName, data); err != nil {
return err
}
}
Expand All @@ -61,23 +66,9 @@ func (c *viewConfig) Parse(data []byte) error {
return yaml.Unmarshal(data, &c)
}

func DiscoverViews(templates []string, repo sparql.Repository, siteConfig config.SiteConfig) ([]View, error) {
func DiscoverViews(templateCollection templates.TemplateCollection) ([]View, error) {
var views []View

var functionMap = map[string]interface{}{
"now": time.Now,
"split": strings.Split,
"replace": strings.Replace,
"lcase": strings.ToLower,
"ucase": strings.ToUpper,
"tcase": strings.Title,
"env": os.Getenv,

"query": repo.InlineQuery,
"config": siteConfig.Get,
"metadata": siteConfig.GetMetadata,
}

err := filepath.Walk("views", func(path string, info os.FileInfo, err error) error {
if info.Mode().IsRegular() {
if filepath.Ext(path) == ".yaml" {
Expand All @@ -100,34 +91,19 @@ func DiscoverViews(templates []string, repo sparql.Repository, siteConfig config
multipageVariableHook = &re.FindAllStringSubmatch(vConfig.Output, 1)[0][1]
}

// #todo this only exists here to raise a good error,
// one should check for the path in the template collection instead
templatePath := "templates/" + vConfig.TemplateFile
if _, err := os.Stat(templatePath); err != nil {
return errors.New("Unable to find the template file for the " + viewPath + " view.")
}

_, file := filepath.Split(templatePath)

// ParseFiles requries the base template as the last item therfore we add it again
templates = append(templates, templatePath)

var TextTemplateA *text_template.Template
var HTMLTemplateA *html_template.Template
if vConfig.Unsafe {
funcMap := text_template.FuncMap(functionMap)
TextTemplateA, err = text_template.New("").Funcs(funcMap).ParseFiles(templates...)
} else {
funcMap := html_template.FuncMap(functionMap)
HTMLTemplateA, err = html_template.New("").Funcs(funcMap).ParseFiles(templates...)
}

if err != nil {
return err
}

view := View{
ViewConfig: vConfig,
HTMLTemplate: HTMLTemplateA,
TextTemplate: TextTemplateA,
HTMLTemplate: templateCollection.ParsedHTMLTemplates,
TextTemplate: templateCollection.ParsedTextTemplates,
TemplateName: file,
MultipageVariableHook: multipageVariableHook,
}
Expand Down