[Answer]-What is wrong with my Django templating use of if's?

1đź‘Ť

âś…

What about using a filter for this:

href="{{ ulr.url|urlize }}"

Remember to check here before to build your own (look for urlize):
https://docs.djangoproject.com/en/dev/ref/templates/builtins/


I think a better approach would be to the save the URLs as absolute ones within the admin and strip “http://” when showing the link…

0đź‘Ť

As an alternative to using inline template statements or template filters, you could create a method/property on the model to handle the url creation logic. Assuming your Url is a model:

class Url(models.model):
    url = model.TextField()

    @property
    def full_url(self):
        if ":" not in url.url:
            ....
        return full_url

And use directly in the templates

    href="{{ url.full_url }}">{{ url.url }}</a>

The templates stay clean and free of “business logic” which can be a good approach e.g. if you have designers creating html/css templates

edit: This also frees you up to perform more advanced logic in the full_url property (like checking for spam, broken links, etc)

👤perrygeo

Leave a comment