Skip to content

Commit 0736950

Browse files
committed
RenderWithRequest, WriteWithRequest, Render
1 parent 6af1361 commit 0736950

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

partial.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -263,11 +263,34 @@ func (p *Partial) getPartialHeader() string {
263263
return ""
264264
}
265265

266+
// RenderWithRequest renders the partial with the given http.Request.
266267
func (p *Partial) RenderWithRequest(ctx context.Context, r *http.Request) (template.HTML, error) {
267268
renderTarget := r.Header.Get(p.getPartialHeader())
268269
return p.renderWithTarget(ctx, r, renderTarget)
269270
}
270271

272+
// WriteWithRequest writes the partial to the http.ResponseWriter.
273+
func (p *Partial) WriteWithRequest(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
274+
out, err := p.RenderWithRequest(ctx, r)
275+
if err != nil {
276+
return err
277+
}
278+
279+
_, err = w.Write([]byte(out))
280+
if err != nil {
281+
return err
282+
}
283+
284+
return nil
285+
}
286+
287+
// Render renders the partial without requiring an http.Request.
288+
// It can be used when you don't need access to the request data.
289+
func (p *Partial) Render(ctx context.Context) (template.HTML, error) {
290+
// Since we don't have an http.Request, we'll pass nil where appropriate.
291+
return p.render(ctx, nil)
292+
}
293+
271294
func (p *Partial) renderWithTarget(ctx context.Context, r *http.Request, renderTarget string) (template.HTML, error) {
272295
if renderTarget == "" || renderTarget == p.id {
273296
out, err := p.render(ctx, r)

service.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,7 @@ func (l *Layout) AddData(key string, value any) *Layout {
117117
return l
118118
}
119119

120+
// RenderWithRequest renders the partial with the given http.Request.
120121
func (l *Layout) RenderWithRequest(ctx context.Context, r *http.Request) (template.HTML, error) {
121122
// Apply configurations to content and wrapper
122123
l.applyConfigToPartial(l.content)
@@ -132,7 +133,26 @@ func (l *Layout) RenderWithRequest(ctx context.Context, r *http.Request) (templa
132133
}
133134
}
134135

136+
// WriteWithRequest writes the layout to the response writer.
137+
func (l *Layout) WriteWithRequest(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
138+
out, err := l.RenderWithRequest(ctx, r)
139+
if err != nil {
140+
return err
141+
}
142+
143+
_, err = w.Write([]byte(out))
144+
if err != nil {
145+
return err
146+
}
147+
148+
return nil
149+
}
150+
135151
func (l *Layout) applyConfigToPartial(p *Partial) {
152+
if p == nil {
153+
return
154+
}
155+
136156
p.fs = l.filesystem
137157
p.functions = l.service.config.FuncMap
138158
p.useCache = l.service.config.UseCache

0 commit comments

Comments
 (0)