mark2web/helper/template_functions.go
Sebastian Frank 39f1932cc3
All checks were successful
continuous-integration/drone/push Build is passing
generate details sites from fnRender
2019-02-28 10:43:30 +01:00

121 lines
2.7 KiB
Go

package helper
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"path"
"strings"
"gitbase.de/apairon/mark2web/config"
"github.com/davecgh/go-spew/spew"
"github.com/extemporalgenome/slug"
"github.com/flosch/pongo2"
)
// RequestFn will make a web request and returns map[string]interface form pongo2
func RequestFn(url *pongo2.Value, args ...*pongo2.Value) *pongo2.Value {
u := url.String()
fmt.Printf("request GET %s\n", u)
resp, err := http.Get(u)
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
spew.Dump(string(body))
if resp.StatusCode >= 400 {
panic(resp.Status)
}
contentType := resp.Header.Get("Content-Type")
if strings.Contains(contentType, "json") {
} else {
panic("invalid content-type")
}
jsonMap := make(map[string]interface{})
err = json.Unmarshal(body, &jsonMap)
if err != nil {
panic(err)
}
return pongo2.AsValue(jsonMap)
}
// RenderFn renders a pongo2 template with additional context
func RenderFn(templateFilename, outDir, subCtxName, ctx *pongo2.Value) *pongo2.Value {
oDirSlug := slug.Slug(outDir.String())
navPath := path.Clean((*currentContext)["CurrentPath"].(string) + "/" + oDirSlug)
outputPath := path.Clean(currentTreeNodeConfig.OutputPath + "/" + oDirSlug)
CreateDirectory(outputPath)
newContext := make(map[string]interface{})
if err := config.Merge(&newContext, *currentContext); err != nil {
Log.Panicf("unable to merge context")
}
newContext[subCtxName.String()] = ctx
newContext["CurrentPath"] = navPath
newNodeConfig := new(config.PathConfigTree)
if err := config.Merge(newNodeConfig, currentTreeNodeConfig); err != nil {
Log.Panicf("unable to merge tree node config")
}
newNodeConfig.OutputPath = outputPath
// remember old to set after recursion
oldContext := currentContext
oldNodeConfig := currentTreeNodeConfig
result, err := RenderTemplate(
templateFilename.String(),
newNodeConfig,
currentPathConfig,
&newContext,
)
if err != nil {
panic(err)
}
currentContext = oldContext
currentTreeNodeConfig = oldNodeConfig
result = FixAssetsPath(
result,
navPath,
)
//spew.Dump(result)
// build output filename
outputFilename := "index.html"
var indexOutputFile *string
if i := currentPathConfig.Index; i != nil {
indexOutputFile = i.OutputFile
}
if indexOutputFile != nil && *indexOutputFile != "" {
outputFilename = *indexOutputFile
}
outFile := outputPath + "/" + outputFilename
Log.Debugf("using '%s' as output file", outFile)
Log.Noticef("writing to output file: %s", outFile)
err = ioutil.WriteFile(outFile, []byte(result), 0644)
if err != nil {
log.Panicf("could not write to output file '%s': %s", outFile, err)
}
return pongo2.AsValue(nil)
}