sklad: highlight matches in the search

This commit is contained in:
Přemysl Eric Janouch 2019-04-18 05:59:13 +02:00
parent cbf8678681
commit 6c6cec6298
Signed by: p
GPG Key ID: A0420B94F92B9493
2 changed files with 17 additions and 2 deletions

View File

@ -2,6 +2,7 @@ package main
import ( import (
"errors" "errors"
"html"
"html/template" "html/template"
"io" "io"
"log" "log"
@ -11,6 +12,7 @@ import (
"os" "os"
"path" "path"
"path/filepath" "path/filepath"
"regexp"
"strings" "strings"
"sync" "sync"
"time" "time"
@ -355,6 +357,19 @@ var funcMap = template.FuncMap{
"lines": func(s string) int { "lines": func(s string) int {
return strings.Count(s, "\n") + 1 return strings.Count(s, "\n") + 1
}, },
"highlight": func(highlight, s string) template.HTML {
b, last := strings.Builder{}, 0
for _, m := range regexp.MustCompile(
`(?i:`+regexp.QuoteMeta(highlight)+`)`).FindAllStringIndex(s, -1) {
b.WriteString(html.EscapeString(s[last:m[0]]))
b.WriteString(`<mark>`)
b.WriteString(html.EscapeString(s[m[0]:m[1]]))
b.WriteString(`</mark>`)
last = m[1]
}
b.WriteString(html.EscapeString(s[last:]))
return template.HTML(b.String())
},
} }
func main() { func main() {

View File

@ -9,7 +9,7 @@
<section> <section>
<header> <header>
<h3><a href="series?prefix={{ .Prefix }}">{{ .Prefix }}</a></h3> <h3><a href="series?prefix={{ .Prefix }}">{{ .Prefix }}</a></h3>
<p>{{ .Description }} <p>{{ .Description | highlight $.Query }}
</header> </header>
</section> </section>
{{ else }} {{ else }}
@ -28,7 +28,7 @@
</h3> </h3>
</header> </header>
{{- if .Description }} {{- if .Description }}
<p>{{ .Description }} <p>{{ .Description | highlight $.Query }}
{{- end }} {{- end }}
</section> </section>
{{ else }} {{ else }}