Skip to content

feat: add render_partial for HTMX fragment responses#355

Open
papilip wants to merge 1 commit intomartenframework:mainfrom
papilip:feature/render-partial
Open

feat: add render_partial for HTMX fragment responses#355
papilip wants to merge 1 commit intomartenframework:mainfrom
papilip:feature/render-partial

Conversation

@papilip
Copy link
Copy Markdown
Contributor

@papilip papilip commented Apr 12, 2026

Summary

Add a render_partial method to Marten::Handlers::Base that renders a template without the layout, context producers, or before_render callbacks.

Motivation

HTMX is increasingly popular for building interactive web applications. A common pattern is returning HTML fragments from handlers to replace parts of the page:

def post
  # Update something...
  render_partial("shared/_item_card.html", context: {item: item})
end

Currently, developers must work around this by manually loading and rendering templates:

tpl = Marten.templates.get_template("shared/_item_card.html")
ctx = Marten::Template::Context{"item" => item}
Marten::HTTP::Response.new(tpl.render(ctx), content_type: "text/html", status: 200)

This is verbose, error-prone, and bypasses the handler's response infrastructure.

Changes

  • src/marten/handlers/base.cr: New render_partial method that creates a clean Context (no producers), renders the template, and returns an HTTP::Response
  • spec/marten/handlers/base_spec.cr: 3 tests (hash context, named tuple context, custom status)

Design decisions

  • No context producers: Partials are fragments — they should not include layout-level data
  • No before_render callbacks: These are designed for full-page renders
  • No request in context: Keeps the partial isolated. If needed, the caller can add it explicitly
  • Supports Hash, NamedTuple, Context, and nil

Related

Test plan

  • Renders template with hash context
  • Renders template with named tuple context
  • Custom status code works
  • All 71 existing handler base tests still pass

Add a render_partial method to Marten::Handlers::Base that renders a
template without the layout, context producers, or before_render
callbacks. This is useful for returning HTML fragments in HTMX responses.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

1 participant