Create a template filter to linkify objects #6231

Closed
opened 2025-12-29 19:38:18 +01:00 by adam · 0 comments
Owner

Originally created by @jeremystretch on GitHub (Mar 18, 2022).

Originally assigned to: @jeremystretch on GitHub.

Proposed Changes

Introduce a linkify template filter that will render a link to an object. For example,

{{ object|linkify }}

would be equivalent to

<a href="{{ object.get_absolute_url }}">{{ object }}</a>

If object does not have a get_absolute_url() method, the filter returns the string representation of object, or None.

Justification

There's a common pattern in templates where we want to link to an object as its string representation. For example:

<a href="{{ object.attr.get_absolute_url }}">{{ object.attr }}</a>

While this isn't terribly obtuse, it can get a bit ugly when we introduce a conditional:

{% if object.attr %}
    <a href="{{ object.attr.get_absolute_url }}">{{ object.attr }}</a>
{% else %}
    {{ ''|placeholder }}
{% endif %}

With a linkify filter in place, we could just do:

{{ object.attr|linkify|placeholder }}
Originally created by @jeremystretch on GitHub (Mar 18, 2022). Originally assigned to: @jeremystretch on GitHub. ### Proposed Changes Introduce a `linkify` template filter that will render a link to an object. For example, ``` {{ object|linkify }} ``` would be equivalent to ``` <a href="{{ object.get_absolute_url }}">{{ object }}</a> ``` If `object` does not have a `get_absolute_url()` method, the filter returns the string representation of `object`, or None. ### Justification There's a common pattern in templates where we want to link to an object as its string representation. For example: ``` <a href="{{ object.attr.get_absolute_url }}">{{ object.attr }}</a> ``` While this isn't terribly obtuse, it can get a bit ugly when we introduce a conditional: ``` {% if object.attr %} <a href="{{ object.attr.get_absolute_url }}">{{ object.attr }}</a> {% else %} {{ ''|placeholder }} {% endif %} ``` With a `linkify` filter in place, we could just do: ``` {{ object.attr|linkify|placeholder }} ```
adam added the status: acceptedtype: housekeeping labels 2025-12-29 19:38:18 +01:00
adam closed this issue 2025-12-29 19:38:19 +01:00
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: starred/netbox#6231