diff --git a/README.md b/README.md index 9518648..f93f98c 100644 --- a/README.md +++ b/README.md @@ -22,13 +22,15 @@ A `fragment` will be hybrid-polymorphic (if this is a thing). On the server it i * `method` can be of `GET` (default) or `POST`. * `primary` denotes a fragment that sets the response code of the page * `id` is an optional unique identifier (optional) +* `ref`is an optional forwar reference to an `id` (optional) * `timeout` timeout of a fragement to receive in milliseconds (default is `300`) * `deferred` is deferring the fetch to the browser * `fallback` is the fallback source in case of timeout/error on the current fragment + ## Example -Import the middleware package this is part of the Fiber web framework +Import the middleware package this is part of the Fiber web framework. ```go package main @@ -69,9 +71,10 @@ app.Listen(":8080") - ``` +The `example` folder contains many examples. You can learn how to use a forward reference of content for fetching outer and inner content and replace either one. + ## Benchmark(s) This is run on a MacBook Pro 16 inch locally. It is the `example` run. diff --git a/example/fragments/fragment4.html b/example/fragments/fragment4.html index ffea93c..2c6cee9 100644 --- a/example/fragments/fragment4.html +++ b/example/fragments/fragment4.html @@ -1,3 +1,4 @@ +

{{ .Title }}

\ No newline at end of file diff --git a/fragment.go b/fragment.go index bda8e12..fb476bb 100644 --- a/fragment.go +++ b/fragment.go @@ -47,20 +47,20 @@ func (h *HtmlFragment) Fragment() *goquery.Document { // Fragments is returning the selection of fragments // from an HTML page. -func (h *HtmlFragment) Fragments() ([]*Fragment, error) { +func (h *HtmlFragment) Fragments() (map[string]*Fragment, error) { h.RLock() defer h.RUnlock() scripts := h.doc.Find("head script[type=fragment]") fragments := h.doc.Find("fragment").AddSelection(scripts) - ff := make([]*Fragment, 0, fragments.Length()) + ff := make(map[string]*Fragment) fragments.Each(func(i int, s *goquery.Selection) { f := FromSelection(s) if !f.deferred { - ff = append(ff, f) + ff[f.ID()] = f } }) diff --git a/resolver.go b/resolver.go index 1ffa40c..d0ccd99 100644 --- a/resolver.go +++ b/resolver.go @@ -41,6 +41,29 @@ func (r *Resolver) Resolve(c *fiber.Ctx, cfg Config, doc *HtmlFragment) (int, [] statusCode = f.statusCode } + fw, err := f.HtmlFragment().Fragments() + if err != nil { + return statusCode, head, err + } + + for _, fwr := range fw { + if fwr.Ref() == "" { + continue + } + + ref, ok := ff[fwr.Ref()] + if !ok { + continue + } + + html, err := ref.HtmlFragment().Html() + if err != nil { + return statusCode, head, err + } + + fwr.Element().ReplaceWithHtml(html) + } + html, err := f.HtmlFragment().Html() if err != nil { return statusCode, head, err