Opened 4 hours ago
Last modified 45 minutes ago
#36941 assigned Cleanup/optimization
Enhancement Proposal for querystring template tag: Support for dynamic context-based keys — at Version 1
| Reported by: | Hristo Trendafilov | Owned by: | |
|---|---|---|---|
| Component: | Template system | Version: | 5.2 |
| Severity: | Normal | Keywords: | |
| Cc: | Yogya Chugh | Triage Stage: | Unreviewed |
| Has patch: | yes | Needs documentation: | no |
| Needs tests: | no | Patch needs improvement: | no |
| Easy pickings: | yes | UI/UX: | no |
Description (last modified by )
Problem Statement
Currently, the {% querystring %} template tag treats the keys in kwargs as static strings. While this works for simple use cases, it severely limits the reusability of templates in component-based architectures.
When using {% include %} to render a reusable component (like a generic filter, a sortable table header, or a pagination widget), the parameter name (the key) often needs to be dynamic, just like the value.
The Use Case
Imagine a reusable include for a sortable column: sort_link.html
<a href="{% querystring sort_param=field_name %}">
Sort by {{ field_label }}
</a>
If we include it like this:
{% include 'sort_link.html' with sort_param='order_by' field_name='price' field_label='By Price' %}
Current Behaviour: It produces ?sort_param=price.
Expected/Desired Behaviour: It should produce ?order_by=price.
Proposed Solution
Add an optional boolean parameter resolve_keys (or similar) to the querystring tag. When set to True, the tag will look up the key names in the current context before processing the query dict.
Alternatively, there could be a dedicated template tag that reuses the current querystring
@register.simple_tag(takes_context=True)
def querystring(context, query_dict=None, resolve_keys=False, **kwargs):
# ... existing logic ...
for _key, value in kwargs.items():
# Look up the key name in context if the flag is True
key = context.get(_key, key) if resolve_keys else _key
if key is None:
# suggested behaviour - remove this key if in parameters, like if passed `key=None`
# ... correct logic continues ...
Benefits
Decoupling: Templates don't need to know the specific backend parameter names.
DRY: One include can handle different filtering/sorting logic across different views.
Consistency: Aligns with how Django handles dynamic values, extending that logic to keys.