Skip to content

Instantly share code, notes, and snippets.

@danjac
Created May 20, 2025 09:53
Show Gist options
  • Save danjac/e621a09c2533aa1bad7f3f0c77f292a5 to your computer and use it in GitHub Desktop.
Save danjac/e621a09c2533aa1bad7f3f0c77f292a5 to your computer and use it in GitHub Desktop.
Simple component tag using Django 5.2 simple_block_tag
@register.simple_block_tag(takes_context=True)
def fragment(
context: Context,
content: str,
fragment_name: str,
**extra_context,
) -> str:
"""Renders a block fragment.
Fragment name is resolved to a template name for example:
{% fragment "pagination.links" id="pagination" %}
my content here...
{% endfragment %}
resolves to the template name "pagination/links.html":
<ul id="{{ id }}">
{{ content }} # content inserted here
</ul>
"""
template = context.template.engine.get_template( # type: ignore[reportOptionalMemberAccess]
_resolve_fragment_template(fragment_name),
)
with context.push(content=content, **extra_context):
return template.render(context)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment