add github stars example
This commit is contained in:
parent
97a48ea9c6
commit
09141314d8
2 changed files with 21 additions and 5 deletions
|
|
@ -43,9 +43,25 @@ func IndexPage(ctx *h.RequestContext) *h.Page {
|
|||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Real Example:**
|
||||
I want to make a navbar that renders how many github stars my repository has. I don't want to make a request to the GitHub API everytime someone visits my page, so I will cache the component for 15 minutes.
|
||||
```go
|
||||
var CachedGithubStars = h.CachedT(time.Minute*15, func(t *h.RequestContext) *h.Element {
|
||||
return GithubStars(t)
|
||||
})
|
||||
|
||||
func GithubStars(ctx *h.RequestContext) *h.Element {
|
||||
stars := http.Get("https://api.github.com/repos/maddalax/htmgo/stargazers")
|
||||
return h.Div(
|
||||
h.Text(stars),
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Note:** We are using CachedT because the component takes one argument, the RequestContext.
|
||||
If the component takes more arguments, use CachedT2, CachedT3, etc.
|
||||
|
||||
**Important**:
|
||||
1. The cached value is stored globally in memory, so it is shared across all requests. Do not store request-specific data in a cached component. Only cache components that you are OK with all users seeing the same data.
|
||||
2. Ensure the declaration of the cached component is **outside the function** that uses it. This is to prevent the component from being redeclared on each request.
|
||||
2. Ensure the declaration of the cached component is **outside the function** that uses it. This is to prevent the component from being redeclared on each request.
|
||||
|
|
|
|||
|
|
@ -17,10 +17,6 @@ var navItems = []NavItem{
|
|||
{Name: "Examples", Url: "/examples"},
|
||||
}
|
||||
|
||||
var CachedStar = h.CachedT(time.Minute*15, func(t *h.RequestContext) *h.Element {
|
||||
return Star(t)
|
||||
})
|
||||
|
||||
func ToggleNavbar(ctx *h.RequestContext) *h.Partial {
|
||||
return h.SwapManyPartial(
|
||||
ctx,
|
||||
|
|
@ -28,6 +24,10 @@ func ToggleNavbar(ctx *h.RequestContext) *h.Partial {
|
|||
)
|
||||
}
|
||||
|
||||
var CachedStar = h.CachedT(time.Minute*15, func(t *h.RequestContext) *h.Element {
|
||||
return Star(t)
|
||||
})
|
||||
|
||||
func Star(ctx *h.RequestContext) *h.Element {
|
||||
|
||||
type Repo struct {
|
||||
|
|
|
|||
Loading…
Reference in a new issue