github.com/cozy/cozy-stack@v0.0.0-20240603063001-31110fa4cae1/web/middlewares/assets.go (about) 1 package middlewares 2 3 import ( 4 "bytes" 5 "fmt" 6 "html/template" 7 8 "github.com/cozy/cozy-stack/model/instance" 9 build "github.com/cozy/cozy-stack/pkg/config" 10 "github.com/labstack/echo/v4" 11 ) 12 13 // FuncsMap is a the helper functions used in templates. 14 // It is filled in web/statik but declared here to avoid circular imports. 15 var FuncsMap template.FuncMap 16 17 var fontsTemplate *template.Template 18 var themeTemplate *template.Template 19 var faviconTemplate *template.Template 20 21 // BuildTemplates ensure that the cozy-ui can be injected in templates 22 func BuildTemplates() { 23 fontsTemplate = template.Must(template.New("fonts").Funcs(FuncsMap).Parse(`` + 24 `<link rel="stylesheet" type="text/css" href="{{asset .Domain "/fonts/fonts.css" .ContextName}}">`, 25 )) 26 themeTemplate = template.Must(template.New("theme").Funcs(FuncsMap).Parse(`` + 27 `<link rel="stylesheet" type="text/css" href="{{asset .Domain "/styles/theme.css" .ContextName}}">`, 28 )) 29 faviconTemplate = template.Must(template.New("favicon").Funcs(FuncsMap).Parse(` 30 <link rel="icon" href="{{asset .Domain "/favicon.ico" .ContextName}}"> 31 {{if .Dev}} 32 <link rel="icon" href="{{asset .Domain "/images/cozy-dev.svg"}}" type="image/svg+xml" sizes="any"> 33 {{else}} 34 <link rel="icon" href="{{asset .Domain "/icon.svg"}}" type="image/svg+xml" sizes="any"> 35 {{end}} 36 <link rel="apple-touch-icon" sizes="180x180" href="{{asset .Domain "/apple-touch-icon.png" .ContextName}}"/> 37 <link rel="manifest" href="{{asset .Domain "/manifest.webmanifest"}}"> 38 `)) 39 } 40 41 // CozyFonts returns an HTML template for inserting the HTML tag for the loading 42 // the CSS file for web fonts (lato and lato-bold). 43 func CozyFonts(i *instance.Instance) template.HTML { 44 buf := new(bytes.Buffer) 45 err := fontsTemplate.Execute(buf, echo.Map{ 46 "Domain": i.ContextualDomain(), 47 "ContextName": i.ContextName, 48 }) 49 if err != nil { 50 panic(err) 51 } 52 return template.HTML(buf.String()) 53 } 54 55 // ThemeCSS returns an HTML template for inserting the HTML tag for the custom 56 // CSS theme 57 func ThemeCSS(i *instance.Instance) template.HTML { 58 buf := new(bytes.Buffer) 59 err := themeTemplate.Execute(buf, echo.Map{ 60 "Domain": i.ContextualDomain(), 61 "ContextName": i.ContextName, 62 }) 63 if err != nil { 64 panic(err) 65 } 66 return template.HTML(buf.String()) 67 } 68 69 // Favicon returns a helper to insert the favicons in an HTML template. 70 func Favicon(i *instance.Instance) template.HTML { 71 buf := new(bytes.Buffer) 72 err := faviconTemplate.Execute(buf, echo.Map{ 73 "Domain": i.ContextualDomain(), 74 "ContextName": i.ContextName, 75 "Dev": build.IsDevRelease(), 76 }) 77 if err != nil { 78 panic(fmt.Sprintf("failed to generate the favicon: %s", err)) 79 } 80 return template.HTML(buf.String()) 81 }